LeetCode 58. Length of Last Word
2017-09-25 本文已影响10人
关玮琳linSir
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;
}