151. Reverse Words in a String (String)

Posted joannae

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了151. Reverse Words in a String (String)相关的知识,希望对你有一定的参考价值。

思路: 本题考查的目的并不是使用字符串的函数。方法是两次reverse,先对每个单词先做一次翻转,然后对整个字符串做一次翻转。

需要注意的是去除extra space,并且对全space字符串、以及最后一个单词要做特殊处理。

class Solution {
public:
    void reverseWords(string &s) {
        int start = 0;
        int end=-1;
        int i = 0;
        int cur = 0; // point to the string with extra space deleted
        
        //ignore space at the beginning
        while(i < s.length() && s[i]== ){
            i++;
        }
        
        for(;i<s.length();i++){
            if(s[i]==  && i+1 < s.length() && s[i+1] == ) continue; //ignore extra space between words
            if(s[i]==  && i+1 == s.length()) break; //ignore final space
            s[cur++] = s[i];
            if(s[i]== ){
                end = cur-2; //end case1: the letter before space 
                reverse(s, start, end);
                start = cur;
            }
        }
        end = cur-1; //end case2: the last not space letter!!!
        if(end == -1) s = ""; //special case: null string!!!
        if(s[i-1] !=  ){ //reverse the last word!!!
            reverse(s,start,end);
        }
        cout << "end=" << end << endl;
        s = s.substr(0, end+1);
        reverse(s,0,end);
    }
    
    void reverse(string &s, int start, int end){
        int l = start;
        int r = end;
        char tmp;
        while(l<r){
            tmp = s[l];
            s[l]=s[r];
            s[r]=tmp;
            l++;
            r--;
        }
    }
};

 

以上是关于151. Reverse Words in a String (String)的主要内容,如果未能解决你的问题,请参考以下文章

151. Reverse Words in a String

151. Reverse Words in a String

151. Reverse Words in a String

leetcode-Reverse Words in a String-151

LeetCode-151-Reverse Words in s String

151. Reverse Words in a String (String)