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

这题很简单,主要是要考虑到某种特殊的情况,如“a ”(a后面有个空格),否则不能accepted。

class Solution {
public:
    int lengthOfLastWord(string s) {
        int len = s.size(), re = 0;
        if(len==0) return 0;
        for(int i = len - 1; i >= 0; i--){
            if(s[i] != ' ') re++;
            else if(re!=0) break;
        }
        return re;
    }
};

相关文章:

  • 2021-08-29
  • 2021-07-19
  • 2022-12-23
  • 2022-12-23
  • 2021-11-30
  • 2021-08-21
猜你喜欢
  • 2021-12-24
  • 2021-05-20
  • 2022-02-05
  • 2022-03-09
相关资源
相似解决方案