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.
分析:
用C++输入输出控制流来做,但是这样做的话,恐怕失去了本身考察的目的和意义。
Total Accepted: 93077 Total Submissions: 596183 Difficulty: Medium
从提交情况来看,本问题并不简单。
如果用C来写的话,能想得到的思路:先全体逆置一遍再局部单次逆置一遍。
LeetCode累觉不爱,这里不再费时间写.......
class Solution {
public:
void reverseWords(string &str) {
istringstream is(str);
str.clear();
string tmpstr;
while(is>>tmpstr)
str=tmpstr+" "+str;
str = str.substr(0, str.size()-1);//按照上面的代码,尾部多了一个空格
}
};
C++引入了ostringstream、istringstream、stringstream这三个类,
要使用他们创建对象就必须包含<sstream>这个头文件。
istringstream类用于执行C++风格的串流的输入操作。
ostringstream类用于执行C++风格的串流的输出操作。
strstream类同时可以支持C++风格的串流的输入输出操作。
istringstream的构造函数原形如下:
istringstream::istringstream(string str);它的作用是从string对象str中读取字符。
#include<iostream>
#include<sstream> //istringstream 必须包含这个头文件
#include<string>
using namespace std;
int main()
{
string str = " You are a student. ";
istringstream is(str);
string s;
while (is >> s)
{
cout << s << endl;
}
system("pause");
return 0;
}
输出
You
are
a
student
注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!
原文地址:http://blog.csdn.net/ebowtang/article/details/50786542
原作者博客:http://blog.csdn.net/ebowtang
本博客LeetCode题解索引:http://blog.csdn.net/ebowtang/article/details/50668895