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
计算最后一个单词的长度。一开始想的很简单 不是空格就c++ 遇到空格就重新计数 但是会出现很多个空格的情况 或者'a ' 这样的话a也算最后一个单词 所以就要忽略空格 判断条件为 这个字母不是空格
public class Solution {
public int lengthOfLastWord(String s) {
if(s==null||s.length()==0)
return 0;
int c=s.charAt(0)==' '?0:1; //因为会遇到全是空格的情况
for(int i=1;i<s.length();i++){
if(s.charAt(i)!=' '){ //忽略掉队空格的判断
if(s.charAt(i-1)==' '){
c=1;
}
else c++;
}
}
return c;
}
}