Leetcode 557 Reverse Words in a String Ⅲ

Leetcode 557 Reverse Words in a String Ⅲ

题目描述

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:

Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"

Note: In the string, each word is separated by single space and there will not be any extra space in the string.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-words-in-a-string-iii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路解析
class Solution:
    def reverseWords(self, s: str) -> str:
        result = s.split()
        for index, item in enumerate(result):
            temp = list(item)
            self.reverseString(temp)
            result[index] = ''.join(temp)
        return ' '.join(result)
        
    def reverseString(self, temp):
        length = len(temp)
        i = 0
        j = length - 1
        while i < j:
            temp[i], temp[j] = temp[j], temp[i]
            i += 1
            j -= 1

时间夫复杂度为 O ( N ) , N 为 字 符 串 长 度 O(N),N为字符串长度 O(N),N,空间复杂度为 O ( N ) O(N) O(N)

注意:python中可变类型传参时为引用传递,不可变类型传参时为值传递

  • 另外,也可以用栈来实现反转,遇到空格就将前面的单词反转
class Solution:
    def reverseWords(self, s: str) -> str:
        s = s + " "
        stack = []
        result = ""
        for item in s:
            stack.append(item)
            if item == ' ':
                while stack:
                    result = result + stack.pop()
        return result[1:]

时间复杂度为 O ( N ) O(N) O(N),空间复杂度为 O ( N ) O(N) O(N)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值