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
.
題意,找到,最后一個' '
后面的單詞,求出它的長度,如果沒有,就返回0。
思路:從后向前遍歷,發現是字母了,觸發標識位,如果還是字母繼續,發現' '
直接停止,返回剛才的單詞的長度。
java代碼:
public int lengthOfLastWord(String s) {
if(s==null || s.length() == 0)
return 0;
int result = 0;
int len = s.length();
boolean flag = false;
for(int i=len-1; i>=0; i--){
char c = s.charAt(i);
if((c>='a' && c<='z') || (c>='A' && c<='Z')){
flag = true;
result++;
}else{
if(flag)
return result;
}
}
return result;
}