Length of Last Word
2013-10-04 06:46
190 查看
Given a string s consists of upper/lower-case alphabets and empty space characters
If the last word does not exist, return 0.
Note: A word is defined as a character sequence consists of non-space characters only.
For example,
Given s =
return
这一题很简单,但是有一个地方很无聊。 就是可能在一个word之后有很多空格,但是当你要得到last word length的时候 是要忽略这些空格的。 所以首先除去末尾的空格。
第三遍:
' ', return the length of last word in the string.
If the last word does not exist, return 0.
Note: A word is defined as a character sequence consists of non-space characters only.
For example,
Given s =
"Hello World",
return
5.
这一题很简单,但是有一个地方很无聊。 就是可能在一个word之后有很多空格,但是当你要得到last word length的时候 是要忽略这些空格的。 所以首先除去末尾的空格。
public class Solution { public int lengthOfLastWord(String s) { // Note: The Solution object is instantiated only once and is reused by each test case. if(s == null || s.length() == 0) return 0; int i = 0; int tail = 0; for(;tail < s.length(); tail ++){ if(s.charAt(s.length() - tail - 1) != ' ') break; } while(i < s.length() - tail) { if(s.charAt(s.length() - tail - i - 1) == ' ') return i; i ++; } return s.length() - tail; } }
第三遍:
public class Solution { public int lengthOfLastWord(String s) { if(s == null || s.length() == 0) return 0; int right = s.length() - 1; while(right > -1 && s.charAt(right) == ' ') right --; int left = right; while(left > -1 && s.charAt(left) != ' ') left --; return right - left; } }
相关文章推荐
- Leetcode: Length of Last Word
- Length of Last Word
- LeetCode 58 Length of Last Word(最后单词的长度)
- leetcode Length of Last Word
- Leetcode_58_Length of Last Word
- LeetCode – Refresh – Length of Last Word
- Length of Last Word -- leetcode
- LeetCode:Length of Last Word
- Length of last word
- Length of Last Word
- Leetcode_Length of Last Word
- LeetCode#58 Length of Last Word
- leetcode 58: Length of Last Word
- Length of Last Word(返回最后一个字母的长度)
- LeetCode 58 Length of Last Word
- leetcode解题方案--058--Length of Last Word
- LeetCode 058 Length of Last Word
- Length of Last Word
- Length of Last Word Java
- Length of Last Word