翻转字符串里的单词

题目

给定一个字符串,逐个翻转字符串中的每个单词。

示例:

输入: “the sky is blue”,
输出: “blue is sky the”.
说明:

无空格字符构成一个单词。
输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
进阶: 请选用C语言的用户尝试使用 O(1) 空间复杂度的原地解法。

解决方案

  1. 字符串分割,以空格划分为每个单词
  2. 使用向量数组保存每个单词
  3. 倒序将向量数组中的单词重新组成字符串
    **注意:**输出最后一个单词是要去掉空格。

代码

//
// Created by HINTS on 2018/12/6.
//
#include <iostream>
#include <string>
#include <vector>
#include <sstream>

using namespace std;

void reverseWords(string &s){
    istringstream in(s);
     s = "";
    vector<string> v;

    string t;
    while(in >> t){
        v.push_back(t);
    }

    for(int i = v.size()-1; i >= 0; i--){

        if(i > 0){
            s += v[i] + " ";
        }else{
            s += v[i];
        }
    }

}

int main(){
    string str = "the sky is blue";
    reverseWords(str);
    cout<<str<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/ILUU121/article/details/84862976
今日推荐