您的位置:首页 > 其它

Length of Last Word

2013-10-04 06:46 190 查看
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.

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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: