
详细思路
逆向遍历,cnt++,如果遇到空格退出输出
精确定义
cnt已经
i需要判断你下标
class Solution { public: int lengthOfLastWord(string s) { int cnt=0; int i=s.size()-1; while(i>=0&&s[i]==' ')i--; for(;i>=0;i--){ if(s[i]==' ')break; cnt++; } return cnt; } };
踩过的坑,处理"a "
while(i>=0&&s[i]==' ')i--;
浙公网安备 33010602011771号