国产探花免费观看_亚洲丰满少妇自慰呻吟_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;}
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 梅州市| 卫辉市| 剑川县| 封丘县| 纳雍县| 盈江县| 旺苍县| 繁峙县| 武功县| 札达县| 绩溪县| 安泽县| 安远县| 宜黄县| 鄯善县| 廉江市| 托克逊县| 油尖旺区| 乡宁县| 夏河县| 油尖旺区| 大兴区| 景谷| 瑞丽市| 拜城县| 临沂市| 东山县| 绥棱县| 同仁县| 息烽县| 和田市| 八宿县| 宜黄县| 张掖市| 平南县| 香港| 沭阳县| 扶余县| 包头市| 沁源县| 固安县|