leecode第五十八题(最后一个单词的长度)

class Solution {
public:
    int lengthOfLastWord(string s) {
        int res=0;
        int len=s.size();
        if(len==0)
            return res;
        
        int index=len-1;
        while(s[index]==' ')//应对“a__”情况
            index--;
        
        for(int i=index;i>=0;i--)
        {
            if(s[i]!=' ')
                res++;
            else
                break;
        }
        
        return res;
    }
};

 分析:

不难。

猜你喜欢

转载自www.cnblogs.com/CJT-blog/p/10807713.html