Given an input string, reverse the string word by word.
For example,
Given s = “the sky is blue”,
return “blue is sky the”.
Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.
对于Java实现,直接分割字符串然后逆序即可。
代码如下:
public class Solution
{
public String reverseWords(String s)
{
if(s==null || s.length()<=0)
return s;
s=s.trim();
String []res=s.split("\\s+");
if(res.length<=1)
return s;
StringBuilder builder=new StringBuilder();
builder.append(res[res.length-1]);
for(int i=res.length-2;i>=0;i--)
builder.append(" "+res[i]);
return builder.toString();
}
}
下面是C++的做法,就是做一个字符串分割,直接使用stringstream来做分割即可,很好用的
代码如下:
#include <iostream>
#include <vector>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <queue>
#include <stack>
#include <string>
#include <climits>
#include <algorithm>
#include <sstream>
#include <functional>
#include <bitset>
#include <numeric>
#include <cmath>
#include <regex>
using namespace std;
class Solution
{
public:
void reverseWords(string &s)
{
stringstream ss(s);
vector<string> res;
string tmp = "";
while (ss >> tmp)
res.push_back(tmp);
if (res.size() ==0)
s = "";
else
{
s = res[res.size() - 1];
for (int i = res.size() - 2; i >= 0; i--)
s += " " + res[i];
}
}
};