题目来源

  • 《编程之法》 第一章 举一反三 习题
  • LeetCode 151

题目描述

输入一个英文句子,翻转句子中单词的顺序。要求单词内字符的顺序不变,句子中单词以空格符隔开。为简单起见,标点符号和普通字母一样处理。例如,若输入“I am a student.” 则输出“student. a am I”;
注意:句子中可能出现连续多个空格如“ I am a student.” 此时翻转结果需要一致,即只有一个空格

思路

三步翻转法的退化版

  1. 自身翻转“I am a student.” 翻转为“I ma a .tneduts”
  2. 全部翻转“I ma a .tneduts”翻转为“student. a am I”

实现

class Solution {
public:
    string pre_process(string &s) {
        string result = "";
        int len = s.length();
        int head_no_blank = 0;
        int tail_no_blank = len - 1;
        //remove the head blankspace
        while(s[head_no_blank++] == ' ');
        //remove the tail blankspace
        while(s[tail_no_blank--] == ' ');
        
        //remove the middle blankspace
        for (int i = head_no_blank; i <= tail_no_blank; i++) {
            if (s[i] == ' '){
                result.push_back(' ');
                while (s[++i]==' ');
                i--;
            }else{
                result.push_back(s[i]);
            }
        }
        return result;
    }
    void reversestring(string &s, int start,int end) {
        if (start >= s.length()) return;
        while (start < end) {
            swap(s[start],s[end]);
            start ++;
            end --;
        }
    }
    string reverseWords(string s) {
        s = pre_process(s);
        int start = 0;
        int len = s.length();
        //reverse every word
        for (int i = 0; i < len; i++) {
            if (s[i] == ' '){
                reversestring(s,start,i-1);
                start = i + 1;
            }
        }
        //reverse the last one
        reversestring(s,start,len - 1);
        
        //reverse all
        reversestring(s,0,len-1);
        return s;
    }
};

int main(){
    std::cout<<Solution().reverseWords("   I am    a   student.")<<std::endl;
    return 0;
}

zer0like
1 声望0 粉丝

no bug no life