- Length of Last Word
Easy
558
2203
Add to List
Share
Given a string s consists of upper/lower-case alphabets and empty space characters ’ ', return the length of last word (last word means the last appearing word if we loop from left to right) in the string.
If the last word does not exist, return 0.
Note: A word is defined as a maximal substring consisting of non-space characters only.
Example:
Input: “Hello World”
Output: 5
思路
倒着count
本来拿到题我想把字符串旋转, 但一想倒着count不是更有效
具体解题
先把单词后边的空格清掉
然后开始计数 直到遇到第一个空格
class Solution {
public int lengthOfLastWord(String s) {
if(s.length() == 0){
return 0;
}
int i = s.length() - 1;
//排除两边的空格
while( i >= 0 && s.charAt(i) == ' '){
i--;
}
int count = 0;
//统计最后一个单词长度
while( i >= 0 && s.charAt(i) != ' '){
i--;
count++;
}
return count;
}
}```