[LeetCode] Length of Last Word

58. Length of Last Word

Given a string s consisting of some words separated by some number of spaces, return the length of the last word in the string.

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

1
2
3
4
5
6
7
8
9
10
class Solution {
public:
int lengthOfLastWord(string s) {
int r = s.length() - 1;
while(r >= 0 and s[r] == ' ') r--;
int l = r;
while(l >= 0 and s[l] != ' ') l--;
return r - l;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/26/PS/LeetCode/length-of-last-word/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.