最后一个单词的长度
题目
给定一个字符串, 包含大小写字母、空格’ ‘,请返回其最后一个单词的长度。
如果不存在最后一个单词,请返回 0 。注意事项
一个单词的界定是,由字母组成,但不包含任何的空格。样例
给定 s = “Hello World”,返回 5。
题解
从后向前遍历,找到第一个字符时开始计数,再向前遍历至第一个空格或结束。
public class Solution {
/**
* @param s A string
* @return the length of last word
*/
public int lengthOfLastWord(String s) {
int count = 0;
for (int i= s.length() - 1;i>=0;i--)
{
if (s.charAt(i) != ' ')
{
while (i >= 0 && s.charAt(i) != ' ')
{
count++;
i--;
}
return count;
}
}
return count;
}
}
Last Update 2016.9.16