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;
    }
};

相关文章:

  • 2022-01-28
  • 2021-07-04
  • 2021-05-24
  • 2021-08-20
  • 2021-12-06
  • 2021-09-11
猜你喜欢
  • 2021-08-21
  • 2021-08-15
  • 2021-12-24
  • 2021-05-17
  • 2022-01-14
  • 2022-02-08
相关资源
相似解决方案