leecode-58. 最后一个单词的长度

给定一个仅包含大小写字母和空格 ‘ ‘ 的字符串 s,返回其最后一个单词的长度。如果字符串从左向右滚动显示,那么最后一个单词就是最后出现的单词。

如果不存在最后一个单词,请返回 0

说明:一个单词是指仅由字母组成、不包含任何空格字符的 最大子字符串。

1
2
3
4
示例:

输入: "Hello World"
输出: 5
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
class Solution:
def lengthOfLastWord(self, s):
if s == None:
return 0
length = 0
ch = 0 # 标记 最后一个不为空格的地方,也可以用循环提出空格
for i in s[::-1]:
if i == ' ' and ch != 0:
return length
elif i ==' ':
continue
else:
ch += 1
length += 1
return length


print(Solution().lengthOfLastWord("hello world"))
print(Solution().lengthOfLastWord("hello wor ld"))

print(Solution().lengthOfLastWord("hello wor ld "))
print(Solution().lengthOfLastWord("he"))
print(Solution().lengthOfLastWord("a "))
# 5
# 2
# 2
# 2
# 1

执行用时:32 ms, 在所有 Python3 提交中击败了93.56%的用户

内存消耗:14.8 MB, 在所有 Python3 提交中击败了11.97%的用户

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public int lengthOfLastWord(String s) {
int end = s.length() - 1;
while(end >= 0 && s.charAt(end) == ' ') end--;
if(end < 0) return 0;
int start = end;
while(start >= 0 && s.charAt(start) != ' ') start--;
return end - start;
}
}

//作者:guanpengchn
//链接:https://leetcode-cn.com/problems/length-of-last-word/solution/hua-jie-suan-fa-58-zui-hou-yi-ge-dan-ci-de-chang-d/