Given a string s consisting of words and spaces, return the length of the last word in the string.
A word is a maximal substring consisting of non-space characters only.
Example 1:
Input: s = "Hello World"
Output: 5
Explanation: The last word is "World" with length 5.
Example 2:
Input: s = " fly me to the moon "
Output: 4
Explanation: The last word is "moon" with length 4.
Scan from right, skip trailing spaces, count word length.
Algorithm:
1class Solution {
2 public int lengthOfLastWord(String s) {
3 int i = s.length() - 1;
4
5 // Skip trailing spaces
6 while (i >= 0 && s.charAt(i) == ' ') {
7 i--;
8 }
9
10 // Count word length
11 int length = 0;
12 while (i >= 0 && s.charAt(i) != ' ') {
13 length++;
14 i--;
15 }
16
17 return length;
18 }
19}