错误代码:
class Solution { public: string ReverseSentence(string str) { int length = str.size(); if(length <= 0) return str; reverse(str,0,length-1); std::queue<int> blank; for(int i = 0;i < length;i++){ if(str[i] == ' ') blank.push(i); } int begin = 0; //int end = blank.front(); //blank.pop(); while(!blank.empty()){ int end = blank.front(); blank.pop(); reverse(str,begin,end-1); begin = end+1; //end = blank.front(); //blank.pop(); } reverse(str,begin,length-1); return str; } private: void reverse(string str,int begin,int end){ while(begin < end){ char tmp = str[begin]; str[begin] = str[end]; str[end] = tmp; begin++; end--; } } };
正确代码:
class Solution { public: string ReverseSentence(string str) { int length = str.size(); if(length <= 0) return str; reverse(str,0,length-1); std::queue<int> blank; for(int i = 0;i < length;i++){ if(str[i] == ' ') blank.push(i); } int begin = 0; //int end = blank.front(); //blank.pop(); while(!blank.empty()){ int end = blank.front(); blank.pop(); reverse(str,begin,end-1); begin = end+1; //end = blank.front(); //blank.pop(); } reverse(str,begin,length-1); return str; } private: void reverse(string &str,int begin,int end){ while(begin < end){ char tmp = str[begin]; str[begin] = str[end]; str[end] = tmp; begin++; end--; } } };
正确代码只是比错误代码在reverse函数中增加了一个参数引用
错误代码使用的reverse函数并不能改变str这个实参,导致后面的翻转出错。增加参数引用后就能对参数str进行改变。