O(1) space C++ solution, Reverse Words in a String


  • -1
    D

    C++ beginner, new to leetcode, any comments are welcome. thanks.

      class Solution {
        public:
            void reverseWords(string &s) {
                int f=0;
                int pos=-1;// where the space should be
                for(int i=0; i<s.size(); i++){
                    if(((!isspace(s[i]))&&i+1==s.size())||((!isspace(s[i]))&&isspace(s[i+1]))){
                        my_reverse(s,f,i+1,pos);
                        pos = pos+i+1-f+1;
                    }else if(isspace(s[i])&&!isspace(s[i+1])){
                        f = i+1;
                    }
                }
                s.resize(max(0,pos));
                reverse(s.begin(),s.end());
            }
        
            // reverse s[f..t] and place it at s[pos..pos+f-t] and fill a space in front if necessary
            void my_reverse(string &s, int f, int t, int pos){
                if(pos!=-1){
                    s[pos] = ' ';
                }
                pos++;
                int i=0;
                for(; pos<f; i++,pos++){
        			s[pos] = s[t-i-1];
        		}
                for(; pos<t-i-1; i++,pos++){
                	char tmp = s[pos];
                    s[pos] = s[t-i-1];
                    s[t-i-1] = tmp;
                }
            }
        };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.