LeetCode58. Length of Last Word
来源:互联网 发布:怪物猎人ol mac 编辑:程序博客网 时间:2024/06/03 20:27
58.Length of Last Word
题意: 给一个字符串,这个字符串包括大小写字母和空格,返回这个字符串的最后一个单词的长度。如果最后一个单词不存在,则返回0.
一个单词是指没有空格的字母串。
For example,
Given s = “Hello World”,
return 5.
我的思路:
这个题很简单,如果输入字符串为空,则返回0;
如果不为空,从最后一位向前数,一直到空格为止的长度就是字符串中最后一个单词的长度;但是这里要考虑一种情况就是字符串末尾是空格,这样要往前推,找到单词的位置。
public int lengthOfLastWord(String s) { int count = 0; if(s.length() == 0){ return 0; } else{ for(int i = s.length() - 1; i >= 0; i--){ if(s.charAt(i) != ' '){ count++; } else{ if(count > 0){ break; } } } return count; }}
第二种方法: 用到了Java中String类的方法
s.trim();去掉字符串首位的空格;
s.trim().lastIndexOf(” “);返回字符串中最后一个空格的索引,若果没有,则返回-1;
public int lengthOfLastWord2(String s) { s = s.trim(); int lastIndex = s.lastIndexOf(' ') + 1; return s.length() - lastIndex; }
第三种写法: 第二种写法的简洁版,看着好牛。
public int lengthOfLastWord1(String s) { return s.trim().length()-s.trim().lastIndexOf(" ")-1;}
阅读全文
0 0
- LeetCode58:Length of Last Word
- Leetcode58 Length of Last Word
- LeetCode58----Length of Last Word
- leetcode58---Length of Last Word
- leetcode58:Length of last word
- Leetcode58: Length of Last Word
- leetcode58: Length of Last Word
- Leetcode58.Length of Last Word
- LeetCode58. Length of Last Word
- LeetCode58 Length of Last Word
- Leetcode58. Length of Last Word
- leetcode58. Length of Last Word
- leetcode58. Length of Last Word
- LeetCode58. Length of Last Word
- Leetcode58-Length of Last Word
- LeetCode58——Length of Last Word
- LeetCode58——Length of Last Word
- Length of Last Word
- 2017腾讯WE大会门票—早鸟票
- Python中的__name__属性
- 记LWIP调试http server的Out of memory问题
- Activity布局加载流程源码解析
- SOFTHEAD 故事
- LeetCode58. Length of Last Word
- oracle分页数据库查询
- HTTPS协议原理
- 批量删除表
- nginx+tomcat+memcache负载均衡动静分离
- js实现html页面转为pdf下载
- 枚举
- Java基础面试之集合框架
- shell中如何取括号中的字符