LeetCode: 557Reverse Words in a String III(easy)

给定一个字符串,你需要反转每个单词内的字符顺序,同时保持空格和初始单词顺序不变。例如:输入'Let's take LeetCode contest',输出'stleL ekat edoCteL ecnats'。题目中指出字符串中单词由单个空格分隔,且无额外空格。注意到原代码运行时间为772ms,而其他人的实现为26ms,说明使用栈可能会导致效率较低。

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

题目:

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.

代码:

class Solution {
public:
    string reverseWords(string s) {
        stack<char> tem;
        string result;
        string s1 = s + ' ';
        for (auto c : s1){
            if ( c != ' ')
                tem.push(c);
            else {
                while(!tem.empty()){
                    result = result + tem.top();
                    tem.pop();
                }
                result = result + ' ';
            }
        }
        result = result.substr(0, result.length()-1);
        return result;
    }
};

运行时间:772ms

别人的:

class Solution {
public:
    
    string reverseWords(string s) {
        string result(s.length(), 32);
        int start = 0;
        int end = s.find(32);
        while (end != -1) {
            for (int i = start; i < end; ++i)
                result[end - (i - start) - 1] = s[i];
            start = end + 1;
            end = s.find(32, start);
        }
        end = s.length();
        for (int i = start; i < end; ++i)
            result[end - (i - start) - 1] = s[i];
        return result;
    }
};

运行时间:26mm

 

栈比较耗时间?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值