Leetcode日练笔记28 #151 #557 Reverse Words in a String & Reverse Words in a String III

#151 Reverse Words in a String

Given an input string s, reverse the order of the words.

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:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值