Skip to content

Commit 80afd92

Browse files
authored
Merge pull request gzc426#12 from Syuan-Cheng/Syuan-Cheng-patch-9
Create syuan.md
2 parents 863bc29 + ab3c764 commit 80afd92

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

2018.12.3-leetcode58/syuan.md

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
##### 题目
2+
```
3+
给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度。
4+
5+
如果不存在最后一个单词,请返回 0 。
6+
7+
说明:一个单词是指由字母组成,但不包含任何空格的字符串。
8+
9+
示例:
10+
11+
输入: "Hello World"
12+
输出: 5
13+
```
14+
##### 代码
15+
```
16+
class Solution {
17+
public int lengthOfLastWord(String s) {
18+
String str=s.trim();
19+
String[] strArray=s.split(" ");
20+
String lastStr=strArray[strArray.length-1];
21+
return lastStr.trim().length();
22+
}
23+
}
24+
```
25+
> 要删除掉字符串中前后的空格
26+
##### 代码2
27+
28+
```
29+
class Solution {
30+
public int lengthOfLastWord(String s) {
31+
String str=s.trim();
32+
if (str==null) {
33+
return 0;
34+
}
35+
int count=0,i=str.length()-1;
36+
while(i>=0){
37+
if (str.charAt(i)!=' ') {
38+
count++;
39+
i--;
40+
}else{
41+
break;
42+
}
43+
}
44+
return count;
45+
}
46+
}
47+
```

0 commit comments

Comments
 (0)