#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;}
新聞熱點
疑難解答