2018-3 reverse words

Posted hisonsandiego

tags:

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

亚麻的OA题

reverse words(leetcode有),要求尽可能time/space efficient

 

1,input的string的前后空格都要去除

2,若是input string 中的俩个word 之间有多个空格, 则仅需要保留一个。

 

Clarification:

 

    • What constitutes a word?
      A sequence of non-space characters constitutes a word.
    • Could the input string contain leading or trailing spaces?
      Yes. However, your reversed string should not contain leading or trailing spaces.
    • How about multiple spaces between two words?
      Reduce them to a single space in the reversed string.

 

class Solution {
public:
    void reverseWords(string &s) {
        if (s.empty()) return ;
        if ( s.size () == 1 && s !=" ") return ; // only one char 
 
        
        //cout <<" the size of the input string is large than 1"<< endl;
        int st =0;
        int ed = s.size ()-1;
        int size = s.size();
        string s2;
        
        while ( st < size  && s[st] ==  ) st++;
        if ( st == size ) { s=""; return ;}
        
        while ( ed >0 && s[ed] ==  ) ed--;
        
        int p1  = ed;
        int p2 = p1;
        cout << " all the sapce is removed, and size is , "<< size << " st is "<< st<<" end is " << ed<<endl;
        while ( p1 >= st  ){
            if (s[p1] ==  ){ p1--; continue ;}
        
            
            p2 = p1;
            while ( p2 >= st ){
              //  cout <<"p2 is " << p2 << " p1 is " << p1 <<endl;
                if ( p2 == st) {//the last char.
               //    cout <<" the last char"<< endl;
                    s2 += s.substr(p2, p1 -p2 +1);
                    s = s2;
                    return ;
                }
                
                if ( s[p2] !=  ) p2 --;
                else{
                     s2 += s.substr(p2+1, p1-p2);
             //        cout << " copy the word "<< s.substr(p2+1, p1-p2) <<" from "<< p2 << " to "<< p1<< endl;;
                     s2 +=  ;
                     p1 = p2;
                    break;
                } 
            }
        }
        //s = s2;
        return ;
    }
};

 

以上是关于2018-3 reverse words的主要内容,如果未能解决你的问题,请参考以下文章

leetcode-151-reverse word in a string

557.Reverse Words in a String III

Word 文档的优秀代码片段工具或插件?

Reverse Words in a String III

Reverse Words in a String

Reverse Words in a String