国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

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;}
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 博爱县| 若尔盖县| 兴文县| 开封县| 张北县| 林周县| 平顶山市| 府谷县| 牡丹江市| 孝感市| 穆棱市| 拜城县| 大同市| 毕节市| 会东县| 会宁县| 饶阳县| 瑞丽市| 桐庐县| 澄江县| 兴义市| 伊吾县| 依安县| 什邡市| 开封县| 济南市| 汉源县| 武汉市| 虹口区| 涿州市| 宁武县| 沙田区| 垫江县| 德化县| 宜章县| 任丘市| 肥东县| 灵武市| 神池县| 姚安县| 淮阳县|