问题
思路
这个题我见的多了,STL算法搞定。
两个问题:
1. 成员函数写成static,否则find_if的第三个参数无法绑定
2. 边界数据,只有空格的情形。
代码
class Solution {
public:
string ReverseSentence(string str) {
typedef string::const_iterator const_iter;
const_iter b = str.begin();
const_iter e = str.end();
string ret;
int first = 1;
while( b != e ){
b = find_if( b, e, legal );
if( b < e ){
const_iter after = find_if( b, e, illegal );
if( ret != "" ) ret = string(b, after) + " " + ret;
else ret = string(b, after) + ret;
b = after;
}
else{
if( 1 == first ) return str;
else first = 2;
}
}
return ret;
}
private:
static bool legal( char ch ){ return !illegal(ch); }
static bool illegal( char ch ){ return isspace(ch); }
};