Skip to content

Commit 6448a37

Browse files
authored
Merge pull request gzc426#293 from luckypgirl/patch-3
Create marguerite.md
2 parents 0d6facf + 73881ca commit 6448a37

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

2018.12.3-leetcode58/marguerite.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
058_(最后一个单词的长度)Length of Last Word
2+
1.1 问题描述
3+
给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度。
4+
如果不存在最后一个单词,请返回 0 。
5+
说明:一个单词是指由字母组成,但不包含任何空格的字符串。
6+
1.2 输入与输出
7+
输入:
8+
string s:仅包含大小写字母和空格 ' ' 的字符串 s
9+
输出:
10+
int:最后一个单词的长度
11+
1.3 样例
12+
1.3.1 样例1
13+
输入: "Hello World"
14+
输出: 5
15+
1.3.2 样例2
16+
输入: "Hello "
17+
输出: 5
18+
19+
java版:
20+
import java.util.Scanner;
21+
public class Main{
22+
public static void main(String[] args) {
23+
Scanner in = new Scanner(System.in);
24+
if(in.hasNext()) {
25+
String[]strings words = in.nextLine().split(" ");
26+
System.out.println(words[words.length-1].length());
27+
}else
28+
System.out.println(0);
29+
}
30+
}
31+
32+
python版:
33+
class Solution:
34+
def lengthOfLastWord(self, s):
35+
return len(s.strip(' ').split(' ')[-1])
36+
//这个写法简单,因为字符串有一个方法是分割字符串方法split(),这里只要用空格将字符串分割然后返回
37+
最后一个字符串的长度即可,另外要注意的是分割之前先用strip()方法将字符串最后的空格删除掉,否则会分割出一个空字符串在最后。

0 commit comments

Comments
 (0)