-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathLeetCode-58-Length-of-Last-Word.java
More file actions
47 lines (40 loc) · 1.27 KB
/
LeetCode-58-Length-of-Last-Word.java
File metadata and controls
47 lines (40 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/*
LeetCode: https://leetcode.com/problems/length-of-last-word/
LintCode: http://www.lintcode.com/problem/length-of-last-word/
JiuZhang: http://www.jiuzhang.com/solutions/length-of-last-word/
ProgramCreek: http://www.programcreek.com/2014/05/leetcode-length-of-last-word-java/
Analysis:
Scan from tail to head. Notice if several tail character is ' '
*/
public class Solution {
// 1.
public int lengthOfLastWord(String s) {
if(s == null || s.length() == 0) return 0;
int length = 0;
for(int i = s.length() - 1; i >= 0; i--){
if(length == 0){
if(s.charAt(i) == ' ') continue;
else length++;
}else{
if(s.charAt(i) == ' ') break;
else length++;
}
}
return length;
}
// 2.
public int lengthOfLastWord(String s) {
if (s == null || s.length() == 0) return 0;
String[] strs = s.split(" ");
if (strs.length > 0) {
return strs[strs.length - 1].length();
}
return 0;
}
// 3.
public int lengthOfLastWord(String s) {
s = s.trim();
int lastIndex = s.lastIndexOf(' ') + 1;
return s.length() - lastIndex;
}
}