Easy java accepted solution! Beats 67% of the solution..Comments welcome for improvement!


  • 1
    C
    public String reverseWords(String s) {
            char[] result = s.toCharArray();
            return reverseWordsHelper(result);
        }
    
        public String reverseWordsHelper(char[] s) {
            int i =0;int j= 0;
            StringBuilder sb = new StringBuilder();
            //reverse the whole sentence
            char[] reversed = reverse(s,i,s.length-1);
            
            //Now reverse the individual words. j moves forward as long as its not a space character. Once j encounters a space, we get the words between i and j to get reversed and once reversed we close the gap between i and j.From here on i and j point to same character if its a space.
            while(j <= reversed.length-1){
                if(reversed[j] == ' '){
                    if(j-i > 0) {
                        reverse(reversed, i, j - 1);
                        i=j;
                    }
                    i++;
                }
                j++;
            }
            
            //reverse the last word
            reverse(reversed, i, j - 1);
    
            //take care of spaces
            int end=0;
            while(end < reversed.length) {
                if(reversed[end] != ' '){
                    sb.append(reversed[end]);
                    if(end < reversed.length-1 && reversed[end+1] == ' ' ) {
                        sb.append(' ');
                    }
                }
                end++;
            }
    
            //cleanup if any space as the last character
            if(sb.length() > 0 && sb.charAt(sb.length()-1) == ' '){
                sb.deleteCharAt(sb.length()-1);
            }
            return sb.toString();
    
        }
    
        //Reverse the part of char array given its start and end index
        public char[] reverse(char[] word, int i, int j){
            while(i <= j){
                char temp = word[i];
                word[i] = word[j];
                word[j] = temp;
                i++;
                j--;
            }
            return word;
        }
    

Log in to reply
 

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