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

#include 
#include 
#include 
#include 
#include 
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 result = split(s , string(" "));
		if(result.empty())
		{
			s = "";//需要设置字符串为空
			return;
		}
2 			beg = pos + splitStr.length();//起始位置等于pos加上长度
*/

class Solution {
public:

	vector split(string str , string splitStr)
	{
		vector 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 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 nums;
	 char str[1024];
	 int num;
	 Solution solution;
	 vector result;
	 while(gets(str) )
	 {
		 string value(str);
		 solution.reverseWords(value);
		 cout << value << endl;
	 }
}

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


你可能感兴趣的:(leecode)