<LeetCode OJ> 151. Reverse Words in a String

151. Reverse Words in a String


Total Accepted: 93077  Total Submissions: 596183  Difficulty: Medium

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值