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.
已开始忘了考虑以空格结尾的串
public class Solution {
public int lengthOfLastWord(String s) {
// Start typing your Java solution below
// DO NOT write main() function
int len = s.length();
boolean last_word = false;
int last_word_pos = len - 1;
for(int i = len - 1; i >= 0 ; i--){
if(!last_word && s.charAt(i) != ' '){
last_word = true;
last_word_pos = i;
}
if(last_word && s.charAt(i) == ' ')
return last_word_pos - i;
if(last_word && i == 0)// s.charAt(i) != ' '
return last_word_pos + 1;
if(!last_word && i == 0)
return 0;
}
return 0;
}
}public class Solution {
public int lengthOfLastWord(String s) {
// Start typing your Java solution below
// DO NOT write main() function
if (s.length() == 0)
return 0;
int i = s.length() - 1;
int count = 0;
while (i >= 0 && s.charAt(i) == ' ')
--i;
if (i == -1)
return 0;
while (i >= 0 && s.charAt(i) != ' ') {
++count;
--i;
}
return count;
}
}

本文介绍了一种计算给定字符串中最后一个单词长度的方法。针对包含大小写字母及空格的字符串,通过从右向左遍历的方式找到最后一个单词,并返回其长度。文章提供了两种实现思路,一种是记录最后一个单词的起始位置并计算长度,另一种是先跳过末尾空格再累加字符数量。
210

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



