从零开始的LC刷题(14): Length of Last Word

原题:

Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.

If the last word does not exist, return 0.

Note: A word is defined as a character sequence consists of non-space characters only.

Example:

Input: "Hello World"
Output: 5

没啥好说的,十分简单,结果:

Success

Runtime: 4 ms, faster than 100.00% of C++ online submissions for Length of Last Word.

Memory Usage: 8.8 MB, less than 100.00% of C++ online submissions for Length of Last Word.

代码:

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

猜你喜欢

转载自blog.csdn.net/cyr429/article/details/89542265