题目描述:
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
思路:
从后往前遍历字符串,以空格来确定单词界限。
实现1:
class Solution {
public int lengthOfLastWord(String s) {
if(s==null||s.trim().length()==0){
return 0;
}
int i=s.length()-1;
int ret=0;
while(i>=0&&s.charAt(i)==' '){
i--;
}
//找到了靠最后的非空格位置所在的索引
//再次遍历找到下一个空格,中间的长度即为所求
while(i>=0){
if(s.charAt(i)==' '){
break;
}
i--;
ret++;
}
return ret;
}
}
实现2:
class Solution {
public int lengthOfLastWord(String s) {
if(s==null||s.trim().length()==0){
return 0;
}
String[] strs=s.split(" ");
if(strs.length==1){
return s.trim().length();
}
return strs[strs.length-1].length();
}
221

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



