forked from chuyi2007/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLengthOfLastWord.java
More file actions
33 lines (32 loc) · 920 Bytes
/
LengthOfLastWord.java
File metadata and controls
33 lines (32 loc) · 920 Bytes
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
public class Solution {
public int lengthOfLastWord(String s) {
// Start typing your Java solution below
// DO NOT write main() function
s = s.trim();
int start = s.length();
for(int i = s.length() - 1; i >= 0; --i){
if(s.charAt(i) == ' '){
start = i + 1;
break;
}
if(i == 0)
start = 0;
}
return s.length() - start;
}
}
public class Solution {
public int lengthOfLastWord(String s) {
// Start typing your Java solution below
// DO NOT write main() function
int end = s.length() - 1;
while(end >= 0 && s.charAt(end) == ' ')
--end;
if(end < 0)
return 0;
int start = end;
while(start >= 0 && s.charAt(start) != ' ')
--start;
return end - start;
}
}