Posted on 2022-11-13 18:56
Uriel 阅读(56)
评论(0) 编辑 收藏 引用 所属分类:
字符串处理 、
闲来无事重切Leet Code
将一串字符以空格分成不同单词,然后倒序输出,可能有连续多个空格,但倒序输出时只保留一个,例如
Input: s = "a good example"
Output: "example good a"
方法一:用Python自带的字符串split(),很方便
1 #151
2 #Runtime: 34 ms
3 #Memory Usage: 13.7 MB
4
5 class Solution(object):
6 def reverseWords(self, s):
7 """
8 :type s: str
9 :rtype: str
10 """
11
12 return ' '.join(s.split()[::-1])
方法二:手工切割字符串
1 #151
2 #Runtime: 49 ms
3 #Memory Usage: 13.6 MB
4
5 class Solution(object):
6 def reverseWords(self, s):
7 """
8 :type s: str
9 :rtype: str
10 """
11 ans = []
12 tp = ""
13 for i in s:
14 if i == ' ':
15 if len(tp) > 0:
16 ans.append(tp)
17 tp = ""
18 else:
19 tp += i
20 if len(tp) > 0:
21 ans.append(tp)
22 tp = " "
23 return ' '.join(ans[i] for i in range(len(ans) - 1, -1, -1))