leetcode Reverse Words in a String

Given an input string, reverse the string word by word.

For example,
Given s = "the sky is blue",
return "blue is sky the".

Clarification:
  • What constitutes a word?
    A sequence of non-space characters constitutes a word.
  • Could the input string contain leading or trailing spaces?
    Yes. However, your reversed string should not contain leading or trailing spaces.
  • How about multiple spaces between two words?
    Reduce them to a single space in the reversed string.

具体实现见代码,值得注意的是在反转的过程中本来用的是char *数组,使用sprintf一直报OLE错误,后来改用string的append就可以了。参考代码两个方法实现,其中第二个参考网上的,效率其实差不多。。。但是代码确实精简很多。。。

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <algorithm>
#include <map>
#include <stack>
#include <cmath>
#include <queue>
#include <set>
#include <list>
#include <cctype>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define REP(i,j,k) for(int i = j ; i < k ; ++i)
#define MAXV (1000)
#define INF (0x6FFFFFFF)
using namespace std;

class Solution
{
public:
    void reverseWords(string &s) {
        bool first = true;
        const char *x = s.c_str();
        int word_start[100000]= {0};//记录一个单词的开始下标
        int word_end[100000]= {0};//记录一个单词的结束下标
        int cnt = 0;
        unsigned i=0;
        for(;;) {
            while(x[i]==' ')//跳过空格
                ++i;
            if(i >= s.size())
                break;
            word_start[cnt] = i;//记录单词的开始位置
            while(x[i]!=' '&&x[i]!='')
                ++i;
            word_end[cnt++] = i-1;//记录单词的结束位置
        }
        string str;
        while(cnt--) {//从后往前将单词append到str中
            char temp_s[100000];//一个单词
            int t=word_end[cnt]-word_start[cnt]+1;
            int temp_cnt=word_start[cnt],j=0;
            for(j=0; j<t; ++j) {
                temp_s[j]=x[temp_cnt++];
            }
            temp_s[j]=0;//位置j置0表示单词结束
            if(first) {
                str.append(temp_s);
                first = false;
            } else
                str.append(" ").append(temp_s);
        }
        s = str;
         cout<<s<<"*111"<<endl;
    }
    void reverseWords1(string &s) {
        string rs;
        for (int i = s.length()-1; i >= 0; ) {
            while (i >= 0 && s[i] == ' ') i--;
            if (i < 0) break;
            if (!rs.empty()) rs.push_back(' ');
            string t;
            while (i >= 0 && s[i] != ' ') t.push_back(s[i--]);
            reverse(t.begin(), t.end());
            rs.append(t);
        }
        s = rs;
        cout<<s<<"*222"<<endl;
    }
};

int main()
{
    //freopen("in.txt","r",stdin);
    Solution s;
    string kk = "  I love!!      you so much   ";
    string k1 = kk;
    string k2 = kk;
    s.reverseWords1(k1);
    s.reverseWords(k2);
    return 0;
}
原文地址:https://www.cnblogs.com/aboutblank/p/3621604.html