LeetCode Day46 length-of-last-word

去掉末尾的空格,计算最后一个单词的长度

class Solution {
public:
    int lengthOfLastWord(string s) {
        if(s.empty()) return {};
        int n=s.size()-1;
        for(;s[n]==' ';n--);
        cout<<n;
        for(int i=n;i>=0;i--){
            if(s[i]==' ') return (n-i);
        }
        return n+1;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_41394379/article/details/84710132