將一串字符以空格分成不同單詞,然后倒序輸出,可能有連續(xù)多個(gè)空格,但倒序輸出時(shí)只保留一個(gè),例如
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))