剑指offer:翻转单词顺序列

时间:2022-12-01 18:59:09


题目描述

牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?

class Solution {
public:
string ReverseSentence(string str) {

int len = str.size();

if (len <=1){
return str;
}

int left = 0, right = len - 1;

reverseStr(str, left, right);

left = 0;
right = 0;
while(right <= len){

//“wonderful”这种情况,也就是处理最后一个词
if (right==len || str[right] == ' ' ){
reverseStr(str, left, right - 1);
right++;
left = right;
}
else{
right++;
}
}
return str;
}
private:
void reverseStr(string &str,int left,int right){
while (left < right){
swap(str[left], str[right]);
left++;
right--;
}
}

};

书上代码
可以发现C++中string是可以访问到size()这个位置的,而且值为’\0’

class Solution {
public:
string ReverseSentence(string str) {

int len = str.size();

if (len <=1){
return str;
}

int left = 0, right = len - 1;

reverseStr(str, left, right);

left = 0;
right = 0;
while(str[left]!= '\0'){

if (str[left] == ' '){
left++;
right++;
}
else if (str[right] == ' ' || str[right] == '\0'){
reverseStr(str, left, --right);
right++;
left = right;
}
else{
right++;
}
}

return str;
}
private:
void reverseStr(string &str,int left,int right){
while (left < right){
swap(str[left], str[right]);
left++;
right--;
}
}

};