题目描述
牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?
参考代码
class Solution {
public:
string ReverseSentence(string str) {
string res = str;
int length = str.length();
if(length == 0)
return res;
mReverse(res, 0, length-1);
int low = 0;
int high = 0;
while(res[low] != '\0'){
if(res[low] == ' '){
low++;
high++;
}else if(res[high] == ' ' || res[high] == '\0'){
mReverse(res, low, --high);
low = ++high;
}else{
high++;
}
}
return res;
}
void mReverse(string &str, int low, int high){
while(low < high){
swap(str[low], str[high]);
low++;
high--;
}
}
};
while
循环那里要仔细考虑一下。