题目:
解答:
从后往前遍历,很容易判定出来。
代码:
class Solution {
public:
int lengthOfLastWord(string s) {
if(s.empty()) return 0;
int index = s.size() - 1;
while(index >= 0 && s[index] == ' ') --index;
if(index < 0) return 0;
int end = index;
while(index >= 0 && s[index] != ' ') --index;
return end - index;
}
};
更新会同步在我的网站更新(https://zergzerg.cn/notes/webnotes/leetcode/index.html)