My Java Solution O(n) time and O(1) space.


  • 1
    P
    int start=0,end;
            s = s.trim().replaceAll(" +", " ");
            for(int i=0;i < s.length(); i++)
            {
                if(s.charAt(i)==' ' || i==(s.length()-1))
                  {
                     if (i==(s.length()-1))
                        end = i;
                     else     
                        end = i-1;
                     
                     s = reverseString(s,start,end);
                     start = i+1;
                  }
            }
            
            return reverseString(s,0,s.length()-1);
            
        }
        
        public String reverseString(String s, int start, int end)
        {
           char[] chararray = s.toCharArray();
            
            for(int i=start;i<start+(end-start+1)/2; i++)
            {
                char temp = chararray[i];
                chararray[i] = chararray[end- i + start];
                chararray[end-i+start] = temp;
            }
            
            return String.valueOf(chararray);
        }

  • 0
    X

    That is not O(n) time and O(1) space solution.
    You used a nested loop so that's a O(n^2) time. And a char[] is used which means O(n) space.


Log in to reply
 

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