数据结构-剑指offer-翻转单词顺序列

题目:例如,“student.a am I”,正确的句子应该是“I am a student.”。

思路:直通BAT关于字符串的视频中有提到类似的题型。对字符串进行两次翻转,第一次对全体字符串进行翻转,第二次以空格为分界线对每个单词进行翻转。

class Solution {
public:
    string ReverseSentence(string str) {
        int len = str.size();
        Reverse(str, 0, len - 1); //先整体翻转
        int blank = -1;
        for(int i = 0;i < len;i++){
            if(str[i] == ' '){ 
                int nextBlank = i;
                Reverse(str,blank + 1,nextBlank - 1);
                blank = nextBlank;
            }
        }
        Reverse(str,blank + 1,len - 1);
        return str;
    }
    void Reverse(string &str,int low,int high){
        //char temp;
        //while(low<high){
            //temp = str[low];
            //str[low] = str[high];
            //str[high] = temp;
            //low++;
            //high--;
        //}
        while(low<high){
            swap(str[low++],str[high--]);
        }
    }
};

猜你喜欢

转载自blog.csdn.net/baidu_32936911/article/details/80640889