File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change
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
+ ```
You can’t perform that action at this time.
0 commit comments