LeetCode: Length of Last Word

LeetCode: Length of Last Word

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

/**
* Created by hzhou on 4/22/15. [email protected]
*/
public class LengthOfLastWord {
public int lengthOfLastWord(String s) {
if (s == null || s.trim().isEmpty()) {
return 0;
}
s = s.trim();
String[] splits = s.split(" ");
for (int i = splits.length - 1; i >= 0; i--) {
if (!splits[i].equals(" ")) {
return splits[i].length();
}
}
return 0;
}
}