快乐的LeetCode --- 151--翻转字符串里的单词 (面试题58 - I. 翻转单词顺序)

题目描述:

给定一个字符串,逐个翻转字符串中的每个单词。
示例 1:

输入: "the sky is blue"
输出: "blue is sky the"

示例 2:

输入: " hello world! "
输出: "world! hello"

解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。

示例 3:

输入: "a good  example"
输出: "example good a"

解释: 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。

说明:

  1. 无空格字符构成一个单词。
  2. 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
  3. 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。

解题思路1:

利用内置 split 方法和 reverse 方法,由于字符之间可能有多余的空格,因此不要以空格进行分割。
Python之字符串转列表(split),列表转字符串(join)


代码1:

class Solution(object):
    def reverseWords(self, s):
        return " ".join(reversed(s.split()))  # 或者这样的写法 return " ".join(s.split()[::-1])

解题思路2:

首先将s按照空格split划分转换为列表,然后对列表中的每个元素strip掉左右空格,再将这个列表反转,最后用单个空格将列表进行拼接


代码2:

class Solution(object):
    def reverseWords(self, s):
        return " ".join(item.strip() for item in s.split()[::-1])

解题思路3:

首先将s中元素的左右空格strip掉,再按照空格split划分转换为列表,再将这个列表反转,最后用单个空格将列表进行拼接


代码3:

class Solution(object):
    def reverseWords(self, s):
        return " ".join(s.strip().split()[::-1])

解题思路4: 先反转字符串再反转每个单词

来源于:leetcode
首先得把字符串转化成其他可变的数据结构,同时还需要在转化的过程中去除空格。
在这里插入图片描述


代码4:

class Solution:
    def trim_spaces(self, s: str) -> list:
        left, right = 0, len(s) - 1
        # remove leading spaces
        while left <= right and s[left] == ' ':
            left += 1

        # remove trailing spaces
        while left <= right and s[right] == ' ':
            right -= 1

        # reduce multiple spaces to single one
        output = []
        while left <= right:
            if s[left] != ' ':
                output.append(s[left])
            elif output[-1] != ' ':
                output.append(s[left])
            left += 1
        print(output)  # ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!']
        return output

    def reverse(self, List, left, right):
        while left < right:
            List[left], List[right] = List[right], List[left]
            left, right = left + 1, right - 1

    def reverse_each_word(self, List):
        n = len(List)
        start = end = 0

        while start < n:
            # go to the end of the word
            while end < n and List[end] != ' ':
                end += 1
            # reverse the word
            self.reverse(List, start, end - 1)
            # move to the next word
            start = end + 1
            end += 1

    def reverseWords(self, s):
        # converst string to char array
        # and trim spaces at the same time
        l = self.trim_spaces(s)

        # reverse the whole string
        self.reverse(l, 0, len(l) - 1)

        # reverse each word
        self.reverse_each_word(l)

        return ''.join(l)


s = Solution()
str = " hello world! "
print(s.reverseWords(str))

题目来源:
https://leetcode-cn.com/problems/reverse-words-in-a-string/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值