自学内容网 自学内容网

Leetcode: 反转字符串中的单词 III

给定一个字符串 s ,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。

思路:遍历字符串,将倒叙的字符插入临时字符串temp,遇到空格为判定条件,将res更新;

#include <iostream>
#include <string>

using namespace std;

class Solution {
public:
    string reverseWords(string s) {
        string temp, res;
        for (auto i : s){
            if (i == ' '){
                res = res + temp + ' ';
                temp.clear();

            }
            else{
                temp.insert(temp.begin(), i);
            }
        }
        return res + temp;
    }
};

int main(){
    Solution s;
    string str = "Let's take LeetCode contest";
    cout << s.reverseWords(str) << endl;
    return 0;
}


原文地址:https://blog.csdn.net/weixin_44379563/article/details/136316429

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!