题解 | #JZ73 翻转单词序列#
翻转单词序列
http://www.nowcoder.com/practice/3194a4f4cf814f63919d0790578d51f3
class Solution {
public:
string ReverseSentence(string str) {
vector<string> strvec;
string ret;
for (size_t pos=0; str.size() && pos!=string::npos; ) {
size_t p = str.find_first_of(' ', pos); //按空格分隔放到向量中
if (p != string::npos) {
strvec.push_back(str.substr(pos, p-pos));
pos = p + 1;
} else {
strvec.push_back(str.substr(pos));
pos = p;
}
}
for (vector<string>::reverse_iterator it=strvec.rbegin(); it!=strvec.rend(); ++it) { //反向遍历并组成字符串
if (ret.size()) ret += " ";
ret += *it;
}
return ret;
}
};
深信服公司福利 891人发布