题解 | #单词倒排#
单词倒排
http://www.nowcoder.com/practice/81544a4989df4109b33c2d65037c5836
#include <iostream> #include <string> using namespace std; class Solution { public: void Word_Inv_Sort(const string& str) { string ans; int n = str.size(); int p1,p2; p1 = p2 = n - 1; while(p2 >= 0) { //如果p1所指向的位置为字母字符 if(Is_Alphabet(str[p1])) { p1--;//一直往前递减 } else { //当前字符不为空格字符 if(str[p1] != ' ') { int Len = p2 - p1; ans += str.substr(p1+1,Len);//取字符串 ans += ' '; p2 = p1 - 1; p1 = p2; } else { //当前字符为空格字符,当且上一字符也不为空格字符时(即:处理连续多个空格情形) if( str[p1+1] != ' ' ) { int Len = p2 - p1; ans += str.substr(p1+1,Len);//取字符串 ans += ' '; p2 = p1 - 1; p1 = p2; } } } } cout << ans << endl; } bool Is_Alphabet(char c) { if(((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')) ) return true; return false; } }; int main() { string str; Solution s; while(getline(cin, str)) { s.Word_Inv_Sort(str); } return 0; }