58. Length of Last Word

BF

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Solution {
public int lengthOfLastWord(String s) {
int length = 0;
int i = s.length() - 1;

// skip the spaces
while (i >= 0 && s.charAt(i) == ' ') {
i--;
}

// count the length
while (i >= 0 && s.charAt(i) != ' ') {
length++;
i--;
}

return length;
}
}

Remarks:

  1. TC: $O(n)$, SC: $O(1)$.