玩命加载中 . . .

58-最后一个单词的长度


LeetCode 58. Length of Last Word

LeetCode-58

Given a string s consists of some words separated by spaces, return the length of the last word in the string. If the last word does not exist, return 0.

A word is a maximal substring consisting of non-space characters only.

Example 1:

Input: s = "Hello World"
Output: 5

Example 2:

Input: s = " "
Output: 0

method

因为后面可能有空格,所以得先找到第一个非空格的元素,再从这个元素开始找是空格的元素

int lengthOfLastWord(string s) {
    int r = s.size() - 1;
    while (r >= 0 && s[r] == ' ') r--;
    int l = r;
    while (l >= 0 && s[l] != ' ') l--;
    return r - l;   // 相当于(l, r]
}

文章作者: kunpeng
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 kunpeng !
  目录