[LeetCode] 58.Length of Last Word
2018-01-30 16:11
357 查看
Given a string s consists of upper/lower-case alphabets and empty space characters ’ ‘, return the length of last word in the string.
If the last word does not exist, return 0.
给定一个字符串s由大/小写字母和空空格字符组成,返回字符串中最后一个单词的长度。
如果最后一个单词不存在,则返回0。
Example:
Input: “Hello World”
Output: 5
这道题很简单,几乎没有难度,之所以记录下来是因为有一种解法比较值得借鉴
这是一种直观的解法:
这是比较值得借鉴的解法,这个解法巧妙地利用了 Java String 的内置方法 trim()
String.trim()用来去除 String 中的空格字符
善于利用语言的内置方法可以很好帮助我们解决实际问题,而不需要自己花时间去实现它
If the last word does not exist, return 0.
给定一个字符串s由大/小写字母和空空格字符组成,返回字符串中最后一个单词的长度。
如果最后一个单词不存在,则返回0。
Example:
Input: “Hello World”
Output: 5
这道题很简单,几乎没有难度,之所以记录下来是因为有一种解法比较值得借鉴
这是一种直观的解法:
class Solution { public int lengthOfLastWord(String s) { int length = 0; boolean flag = false; for (int i = 0; i < s.length(); i++){ if (s.charAt(i) == ' '){ flag = true; }else{ if (flag) { length = 0; flag = false; } length++; } } return length; } }
这是比较值得借鉴的解法,这个解法巧妙地利用了 Java String 的内置方法 trim()
String.trim()用来去除 String 中的空格字符
class Solution { public int lengthOfLastWord(String s) { if(s == null) return 0; return s.trim().length() - s.trim().lastIndexOf(' ') - 1; } }
善于利用语言的内置方法可以很好帮助我们解决实际问题,而不需要自己花时间去实现它
相关文章推荐
- LeetCode-58.Length of Last Word
- [LeetCode] 58.Length of Last Word
- [LeetCode] 58.Length of Last Word
- [LeetCode] 58.Length of Last Word
- [LeetCode] 58.Length of Last Word
- [leetcode:python]58.Length of Last Word
- leetcode - 58.Length of Last Word
- [LeetCode] 58.Length of Last Word
- [LeetCode] 58.Length of Last Word
- Leetcode58.Length of Last Word
- leetCode 58.Length of Last Word (最后单词的长度) 解题思路和方法
- [LeetCode] 58.Length of Last Word
- leetCode 58.Length of Last Word (最后单词的长度) 解题思路和方法
- [LeetCode] 58.Length of Last Word
- [LeetCode] 58.Length of Last Word
- [LeetCode]58.Length of Last Word
- [leetcode] 58.Length of Last Word
- 【LeetCode从零单排】No58.Length of Last Word
- leetcode:Length of Last Word
- LeetCode 57 Length of Last Word