[LeetCode] 557. Reverse Words in a String III 翻转字符串中的单词 III

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.

151. Reverse Words in a String186. Reverse Words in a String II 的类似题目,这题是让翻转字符串里的单词。

 

Python:One Place

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution(object):
    def reverseWords(self, s):
 
        def reverse(s, begin, end):
            for i in xrange((end - begin) // 2):
                s[begin + i], s[end - 1 - i] = s[end - 1 - i], s[begin + i]
 
        s, i = list(s), 0
        for j in xrange(len(s) + 1):
            if j == len(s) or s[j] == ' ':
                reverse(s, i, j)
                i = j + 1
        return "".join(s)

Python:New Array

1
2
3
4
class Solution2(object):
    def reverseWords(self, s):
        reversed_words = [word[::-1] for word in s.split(' ')]
        return ' '.join(reversed_words)

C++:

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
    string reverseWords(string s) {
        for (int i = 0, j = 0; j <= s.length(); ++j) {
            if (j == s.length() || s[j] == ' ') {
                reverse(s.begin() + i, s.begin() + j);
                i = j + 1;
            }
        }
        return s;
    }
};

     

类似题目:

[LeetCode] 151. Reverse Words in a String 翻转字符串中的单词

[LeetCode] 186. Reverse Words in a String II 翻转字符串中的单词 II

All LeetCode Questions List 题目汇总

 

posted @   轻风舞动  阅读(259)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示