首页 > 学院 > 开发设计 > 正文

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

2019-11-08 01:47:51
字体:
来源:转载
供稿:网友
#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 theblue 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;}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表