Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
51 lines (41 loc) · 1.33 KB

File metadata and controls

51 lines (41 loc) · 1.33 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
51
package Algorithms.string;
public class LengthOfLastWord {
public static void main(String[] strs) {
String s = " the book ";
System.out.println(lengthOfLastWord1(s));
}
// solution 1
public static int lengthOfLastWord1(String s) {
if (s == null || s.length() == 0) {
return 0;
}
/*
这里有个规则,它乍看之下很古怪,但很少造成问题:Split会保留开头处的空字段,却舍去结尾处的空字段。例如:
my @fields = split /:/, “:::a:b:c:::”; #得到(“”,“”,“”,“a”,“b”,“c”)
*/
String[] strs = s.split("\\s+");
int size = strs.length;
if (size == 0) {
return 0;
}
int len = strs[size - 1].length();
return len;
}
// solution 2
public int lengthOfLastWord(String s) {
if (s == null || s.length() == 0) {
return 0;
}
// remove the spaces at the end.
String strs = s.trim();
int len = strs.length();
int ret = 0;
for (int i = len - 1; i >= 0; i--) {
if (strs.charAt(i) == ' ') {
return ret;
}
ret++;
}
return len;
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.