题目:
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
.
这题比较简单,只需要注意字符串最前面的空格符以及字符串最后的空格符就行了
我们可以用ret保存字符长度,逢空格清零,并且用pre保存上一个非零的ret,这样一旦字符串以空格结尾,我们返回pre即可
public class No57_LengthOfLastWord {
public static void main(String[] args){
System.out.println(lengthOfLastWord(" hsaifh8732^&*^* a "));
}
public static int lengthOfLastWord(String s) {
int ret = 0;
int pre = 0;
for(int i=0;i<s.length();i++){
if(s.charAt(i) == ' '){
pre = ret==0?pre:ret;
ret = 0;
}
else ret++;
}
return ret==0?pre:ret;
}
}