LeetCode 58. Length of Last Word
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]
}