leecode 解题总结:151. Reverse Words in a String

本文介绍了一种使用C++实现的字符串逆序方法,重点在于如何按单词逆置字符串,并处理多个连续空格及首尾空格的问题。通过示例代码展示了如何分割字符串并逆序输出。
#include <iostream>
#include <stdio.h>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
/*
问题:
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.

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.

分析:trailing space尾部空格
将给定字符串中的单词逆置,注意只是逆置单词的位置,单词本身并不会逆置。
不能包含尾部空格。两个单词间的多个空格需要删除,只保留一个。
明显的按照空格切分,切分逆序遍历输出即可

输入:
the sky is blue
  the  sky is blue 
  (空字符串)
输出:
blue is sky the
blue is sky the

关键:
1 易错,如果字符串多个空格,直接令原始字符串为空
		vector<string> result = split(s , string(" "));
		if(result.empty())
		{
			s = "";//需要设置字符串为空
			return;
		}
2 			beg = pos + splitStr.length();//起始位置等于pos加上长度
*/

class Solution {
public:

	vector<string> split(string str , string splitStr)
	{
		vector<string> result;
		if(str.empty())
		{
			return result;
		}
		if(splitStr.empty())
		{
			result.push_back(str);
			return result;
		}
		int beg = 0;
		size_t pos = str.find(splitStr , beg);
		string partialStr;
		while(string::npos != pos)
		{
			//切分字符串
			partialStr = str.substr(beg , pos - beg);
			if(!partialStr.empty())
			{
				result.push_back(partialStr);
			}
			beg = pos + splitStr.length();//起始位置等于pos加上长度
			pos = str.find(splitStr , beg);
		}
		//切分最后一次的结果
		partialStr = str.substr(beg , pos - beg);
		if(!partialStr.empty())
		{
			result.push_back(partialStr);
		}
		return result;
	}

    void reverseWords(string &s) {
        if(s.empty())
		{
			return;
		}
		vector<string> result = split(s , string(" "));
		if(result.empty())
		{
			s = "";//需要设置字符串为空
			return;
		}
		int size = result.size();
		stringstream stream;
		//切分后的字符串,从后到前遍历
		for(int i = size - 1; i >= 0 ; i--)
		{
			if(i != size - 1)
			{
				stream << " " << result.at(i);
			}
			else
			{
				stream << result.at(i);
			}
		}
		s = stream.str();
    }
};


void process()
{
	 vector<int> nums;
	 char str[1024];
	 int num;
	 Solution solution;
	 vector<int> result;
	 while(gets(str) )
	 {
		 string value(str);
		 solution.reverseWords(value);
		 cout << value << endl;
	 }
}

int main(int argc , char* argv[])
{
	process();
	getchar();
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值