反转字符串中的单词

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

示例 1:

输入: "Let's take LeetCode contest"
输出: "s'teL ekat edoCteeL tsetnoc" 
注意:在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。

class Solution {
public:
  
    string reverseWords(string s) {
        string result;
        int first = 0;
        int second = 0;
        for(int i = 0; i < s.size(); i++){
            if(s[i] == ' '){
                second = i;
                string temp = s.substr(first,second-first);
                temp = singleWord(temp);
                result += temp;
                result += ' ';
                first = i+1;
            }
            if(i == s.size()-1){
                second = s.size();
                string temp = s.substr(first, second-first);
                temp = singleWord(temp);
                result += temp;
              
            }
           
        }
         return result;
    }
    //反转单个单词
    string singleWord(string& s){
        for(int i =0; i < s.size()/2; i++)
        {
            char temp = s[s.size()-1-i];
            s[s.size()-1-i] = s[i];
            s[i] = temp;
        }
        return s;
    }
     
};

看到有的人使用了字符串的reverse函数

class Solution {
public:
    string reverseWords(string s) {
        s = s + ' ';
        auto begin = s.begin(), end = s.begin();
        while(end != s.end()) {
            if(*end == ' ') {
                reverse(begin, end);
                begin = end+1;
            }
            ++end;
        }
        s.erase(end-1);
        return s;
    }
};

//作者:pu-shang-qing-feng
The Safest Way to Get what you Want is to Try and Deserve What you Want.
原文地址:https://www.cnblogs.com/Shinered/p/11413422.html