題目:
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
思路很簡單,先過濾最後的空格,然後在根據字符不是空格來求最後一個單詞的長度
c++:
class Solution {
public:
int lengthOfLastWord(string s) {
int right = s.size() - 1;
int res = 0;
while(right >= 0 && s[right] == ' ') --right;
while(right >= 0 && s[right] != ' '){
--right;
res++;
}
return res;
}
};
java:
class Solution {
public int lengthOfLastWord(String s) {
int right = s.length() - 1;
int res = 0;
while(right >= 0 && s.charAt(right) == ' ') --right;
while(right >= 0 && s.charAt(right) != ' '){
--right;
res++;
}
return res;
}
}
python:
class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
right = len(s) - 1;
res = 0
while right >= 0 and s[right] == ' ': right -= 1
while right >= 0 and s[right] != ' ':
right -= 1
res += 1
return res