【leetcode】58-LengthofLastWord

problem

Length of Last Word

只有一个字符的情况;

最后一个word至字符串末尾之间有多个空格的情况;

code1

class Solution {
public:
    int lengthOfLastWord(string s) {
        if(s.size()==0) return 0;
        int len = 0;
        int right = s.size()-1;
        while(right>=0 && s[right]==' ') right--;//
        for(int i=right; i>=0; i--)
        {
            if(s[i]==' ') break;
            len++;
        }
        return len;
    }
};

code2

class Solution {
public:
    int lengthOfLastWord(string s) {
        if(s.size()==0) return 0;
        int len = 0;
        int right = s.size()-1;
        while(right>=0 && s[right]==' ') right--;//
        while(right>=0 && s[right]!=' ')
        {
            right--;
            len++;
        }
        return len;
    }
};

发现while循环好像比for循环要快。。。

题目求解的是最后一个word的长度,所以还要考虑最后一个word之后还有空格的情况。

参考

1.leetcode;

2.GrandYang_cnblogs;

原文地址:https://www.cnblogs.com/happyamyhope/p/9986965.html