58. Length of Last Word
Problem
Return the length of the last word in s, where words are maximal runs of non-space characters. s may have leading, trailing or repeated spaces.
Example: " fly me to the moon " → 4
Scan from the end: skip trailing spaces, then count characters until the next space. No split, O(1) extra space.
Complexity: O(n).
class Solution:
def lengthOfLastWord(self, s: str) -> int:
i = len(s) - 1
while i >= 0 and s[i] == " ":
i -= 1
j = i
while j >= 0 and s[j] != " ":
j -= 1
return i - j
assert Solution().lengthOfLastWord("Hello World") == 5
assert Solution().lengthOfLastWord(" fly me to the moon ") == 4
assert Solution().lengthOfLastWord("luffy is still joyboy") == 6
assert Solution().lengthOfLastWord("a") == 1
class Solution {
public int lengthOfLastWord(String s) {
int i = s.length() - 1;
while (i >= 0 && s.charAt(i) == ' ') i--;
int j = i;
while (j >= 0 && s.charAt(j) != ' ') j--;
return i - j;
}
}
func lengthOfLastWord(s string) int {
i := len(s) - 1
for i >= 0 && s[i] == ' ' {
i--
}
j := i
for j >= 0 && s[j] != ' ' {
j--
}
return i - j
}