58最后一个单词的长度

class Solution {
public:
    int lengthOfLastWord(string s) {
        int i = s.length()-1, flag = 0,count = 0;
        for(;i>=0;i--)
        {
            if(s[i]==' '&& count ==0)
                continue;
            if(s[i]==' ' && count != 0)
                break;
            count++;
        }
        return count;
    }
};

思路:

从最后一个开始算起,用count表示单词长度并初始化为0

如果s[i]是空格并且count == 0的话,就跳过,一直到s[i]是空格并且count != 0为止

最后返回count就行

猜你喜欢

转载自blog.csdn.net/weixin_40673608/article/details/83069433
今日推荐