忽略最后的一堆(或没有)空格,然后往前遍历,直到遍历完或者遍历到空格结束
class Solution {
public:
int lengthOfLastWord(string s) {
int ans=0;
while(!s.empty() && s.back()==' ') s.pop_back();
while(!s.empty() && s.back()!=' ') s.pop_back(),++ans;
return ans;
}
};