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]!='