-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLengthOfLastWord.java
More file actions
41 lines (37 loc) · 902 Bytes
/
LengthOfLastWord.java
File metadata and controls
41 lines (37 loc) · 902 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
34
35
36
37
38
39
40
41
package com.leetcode;
/**
* Created by jamylu on 2018/3/5.
* leetcode058
*/
public class LengthOfLastWord {
public static void main(String[] args) {
String s = "hello world ";
System.out.println(lengthOfWord(s));
}
// 分割
public int lengthOfLastWord(String s) {
String words[] = s.split(" ");
if (words.length == 0)
return 0;
else
return words[words.length - 1].length();
}
// 从后往前两次遍历
public static int lengthOfWord(String s) {
int i = s.length() - 1;
int len = 0;
for (; i > -1; i--) {
if (s.charAt(i) != ' ') {
break;
}
}
for (; i > -1; i--) {
if (s.charAt(i) != ' ') {
len++;
} else {
break;
}
}
return len;
}
}