-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path058. Length of Last Word
50 lines (40 loc) · 1008 Bytes
/
058. Length of Last Word
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
48
49
50
//Java solution01:
public class Solution {
public int lengthOfLastWord(String s) {
int len = s.length();
if(s == null ||len == 0) {return 0;}
int result = 0;
for(int i = len - 1; i >= 0; i--){
if (s.charAt(i) != ' ') {
result++;
}
else if(s.charAt(i) == ' ' && result != 0){
return result;
}
}
return result;
}
}
//Java solution02:
public class Solution
{
public int lengthOfLastWord(String s)
{
int len = s.length();
int result = 0;
int i = len - 1;
if(s == null ||len == 0) {return 0;}
// ignore the trailing whitespace
while(i >= 0 && s.charAt(i) == ' ')
{
i--;
}
// count from tail until whitespace
while(i >= 0 && s.charAt(i) != ' ')
{
i--;
result++;
}
return result;
}
}