Lintcode 927. Reverse Words in a String II (Medium) (Python)

本文介绍了一种在不分配额外空间的情况下,实现字符串中单词逐个反转的方法。通过定义单词为不含空格字符的序列,该算法能够高效地完成任务。举例来说,输入字符串“theskyisblue”,反转后的结果为“blueisskythe”。文章还提供了Python实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Reverse Words in a String II

Description:

Given an input character array, reverse the array word by word. A word is defined as a sequence of non-space characters.

The input character array does not contain leading or trailing spaces and the words are always separated by a single space.

Example
Given s = “the sky is blue”,
after reversing : “blue is sky the”

Challenge
Could you do it in-place without allocating extra space?

Code:

class Solution:
    """
    @param str: a string
    @return: return a string
    """
    def reverseWords(self, str):
        # write your code here
        def reverse(s):
            tmp = ""
            for i in range(len(s)-1, -1, -1):
                tmp = tmp + s[i]
            return tmp
        strList = str.split(" ")
        res = []
        for i in strList:
            res.append(reverse(i))
        str2 = " ".join(res)
        return reverse(str2)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值