422. 最后一个单词的长度
给定一个字符串, 包含大小写字母、空格' '
,请返回其最后一个单词的长度。
如果不存在最后一个单词,请返回 0
。
class Solution {
public:
/*
* @param s: A string
* @return: the length of last word
*/
int lengthOfLastWord(string &s) {
// write your code here
int size = s.length();
//找到最后一个不是空格的字母
bool isStart = false;
int length = 0;
for (int i = size - 1; i >= 0; i--) {
if (check(s[i])) {
if (!isStart) {
isStart = true;
}
length++;
} else {
if (isStart) {
return length;
}
}
}
return length;
}
bool check(char ch) {
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
return true;
return false;
}
};