C++ simple code - Takes care of leading/trailing whitespaces as well


  • 0
    E
    class Solution {
    public:
        bool isWhiteSpace(char c) {
            return isspace(c);   
        }
        
        void reverse(string& s, int start, int end) {
            while(start<end) {
                char temp = s[end];
                s[end--] = s[start];
                s[start++] = temp;
            }
        }
    
        string reverseWords(string s) {
            int size = s.length();
    
            // trivial cases
            if (size<2)
                return s;
    
            // main logic here
            int last_space = -1;
            for (int i=0; i<=size; i++) {
                // separate way to handle i==size
                if (i==size) {
                    reverse(s, last_space+1, i-1);
                }
                else if ( isWhiteSpace(s[i]) ) {
                    // check the offset of i from change_from
                    if ( !( i-last_space < 2 ) ) {
                        reverse(s, last_space+1, i-1);
                    }
                    last_space = i;
                }
            }
    
            // return final result
            return s;
        }
    };
    

Log in to reply
 

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