LeetCode(58)-Length of Last Word
阿新 • • 發佈:2018-11-06
58. Length of Last Word
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.
Example:
Input: “Hello World”
Output: 5
好吧,這個題很簡單,給一個字串,然後求出最後一個單詞的長度
public int lengthOfLastWord(String s){
int len=0;
for (int i =s.length()-1; i>0; i--) {
if(' '==s.charAt(i)){
if(len==0)continue;
return len;
}
len++;
}
return len;
}