#151 Reverse Words in a String
Given an input string
s
, reverse the order of the words.A word is defined as a sequence of non-space characters. The words in
s
will be separated by at least one space.Return a string of the words in reverse order concatenated by a single space.
Note that
s
may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.
解题思路:
1.去掉头尾多余的空格
2.以white space为分界把string转成单个词的list
3.以white space为连接符把上一步得到的list里所有单词倒序后连起来。
class Solution:
def reverseWords(self, s: str) -> str:
x = s.strip()
y = x.split()
return ' '.join(y[::-1])
runtime:
7ms的solution,直接split(),不用strip()了。
还有一点要注意,[::-1]是直接生成了一个新的reversed list, 不是in-place reversal。要用.reverse()才是in-place reversal。
不过Leetcode里只能用reversed()?用reverse()会出现error?
【有一种解释是只能用在list上。属于list的method。但题目强调了s里至少有一个单词啊?】
两者的区别和sorted() vs .sort()相似。
前者生成新的list,后者直接在original的list上改变。
有一点不理解的是,论坛里的人提到了说面试时,很多interviewer不接受built-in 的method?
#557 Reverse Words in a String III
Given a string
s
, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
解题思路:
用双指针标记每个单词的起点和终点,然后用new记录每个反转后的单词,非单词的地方不改变。
class Solution:
def reverseWords(self, s: str) -> str:
# identify each word before a white space
left = right = 0
new = ''
s += ' '
while right < len(s)-1:
# leave heading spaces until left pointer finds the starting point
while s[left] == ' ':
left += 1
new += s[right:left]
right = left
# right pointer finds the ending point
while s[right] != ' ' and right < len(s)-1:
right += 1
# reverse the word
new += s[left:right][::-1]
# next round
left = right
return new
runtime:
参考20ms:
这里是利用了题目说的within a sentence.所以默认每个单词之间的空格都是1个,头尾无多余的空格。所以可以直接split以及join。
重写一遍:
class Solution:
def reverseWords(self, s: str) -> str:
s = s.split()
s = [i[::-1] for i in s]
s = ' '.join(s)
return s
runtime: