Very easy to understand O(n) space solution using char[] array in Java


  • 1
    T
    public class Solution {
        public String reverseWords(String s) {
            s = s.replaceAll(" +"," ");
            char[] c = s.toCharArray();
            reverse(c,0,c.length-1);
            
            int i =0;
            int j = 0;
            while(i<c.length){
                
                if(c[i]==' '){
                    reverse(c,j,i-1);
                    j=i+1;
                }
                i++;
            }
            reverse(c,j,i-1);
            return new String(c).trim();
            
        }
        
        public void reverse(char[]c, int start, int end){
            while(start<end){
                char temp = c[start];
                c[start]=c[end];
                c[end] = temp;
                start++;
                end--;
            }
        }
    }
    

  • 0
    P

    Thank you for your awesome answer!


Log in to reply
 

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