给定一个仅包含大小写字母和空格 ' '
的字符串,返回其最后一个单词的长度。
如果不存在最后一个单词,请返回 0 。
python:
class Solution:
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
n = len(s)
if n == 0:
return 0
while s[n - 1] == ' ':
n -= 1
if n == 0:
return 0
i = n - 1
res = 0
while i >= 0:
if s[i] != ' ':
res += 1
i -= 1
else:
break
return res
C++:
class Solution {
public:
int lengthOfLastWord(string s) {
int n = s.length();
if(n == 0) return 0;
while(s[n - 1] == ' '){
n -= 1;
if(n == 0) return 0;
}
int i = n - 1,res = 0;
while(i >= 0){
if(s[i] != ' '){
res += 1;i -= 1;
}
else break;
}
return res;
}
};