题目:
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;
}
}
本文介绍了一种简单的方法来求解给定字符串中最后一个单词的长度。该方法通过遍历字符串并处理空格来确定单词边界,最终返回最后一个单词的长度。
:Length of Last Word&spm=1001.2101.3001.5002&articleId=38445475&d=1&t=3&u=73530a89a267494fa1bda1ce925be82f)
9904

被折叠的 条评论
为什么被折叠?



