Description
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
/*
很多其他语言的libary都会有去除string类的首尾空格的库函数,但是标准C++的库却不提供这个功能。
但是C++string也提供很强大的功能,实现trim这种功能也不难。
*/
#include <iostream>
#include <string>
#include <cstring>
#include <tchar.h> // for "_T" declare
#include <vector>
using namespace std;
class Solution {
public:
string reverseWords(string &s) {
// write your code here
string revWords = "";
string TrimRes = Trim(s);
vector<string> DelimStr = Split(TrimRes, " ");
revWords = DelimStr[DelimStr.size()-1];
for(int i=DelimStr.size()-2; i>=0; i--)
{
//revWords = DelimStr[i] + " " + revWords;
revWords = revWords + " " + DelimStr[i];
}
return revWords;
}
string & Trim(string &str)
{
if(str.empty())
return str;
str.erase(0, str.find_first_not_of(" "));
str.erase(str.find_last_not_of(" ") + 1);
return str;
}
vector<string> Split(const string &str, const string &delim)
{
vector<string> res;
if(str == "")
return res;
char *strs = new char[str.length() + 1];
strcpy(strs, str.c_str());
char *d = new char[delim.length() + 1];
strcpy(d, delim.c_str());
char *p = strtok(strs, d);
while(p)
{
string s = p;
res.push_back(s);
//res = res + " " + s;
p = strtok(NULL, d);
}
return res;
}
};
int main()
{
string s1 = " the sky is blue! one parameter ll? ";
Solution slu;
string s2 = slu.reverseWords(s1);
cout<<"The Reverse Words is:"<<endl;
cout<<s2<<endl;
}