题目:
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) {
int temp = s.length()-1, len = 0;
while(temp >= 0 && s.charAt(temp) == ' ') {
temp -= 1;
}
while(temp >= 0 && s.charAt(temp--) != ' ') {
len++;
}
return len;
}
}
Python实现:
class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
i = len(s) - 1
num = 0
while i >= 0 and s[i] == ' ':
i -= 1
while i >= 0 and s[i] != ' ':
num += 1
i -= 1
return num