Leetcode:58. Length of Last Word

Description

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

Given s = "Hello World",
return 5.

思路

  • 没啥好说的

代码

class Solution {
public:
    int lengthOfLastWord(string s) {
        int len = s.size();
        if(len == 0) return 0;
        
        int i = len - 1;
        while(i >= 0 && s[i] == ' ')
            i--;
        
        int end = i;
        while(i >= 0 && s[i] != ' ')
            i--;
        
        return end - i;
    }
};
原文地址:https://www.cnblogs.com/lengender-12/p/6876083.html