58. Length of Last Word

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public int lengthOfLastWord(String s) {
int j = s.length() - 1;
while (s.charAt(j) == ' ') {
j--;
}

// 此时 j 指向英文字母
int i = j;
while (i >= 0 && s.charAt(i) != ' ') {
i--;
}

// 此时 i 指向空格或越界
return j - i;
}
}

References

58. Length of Last Word