Clean Java solution. Beats 75% solutions


  • 0
    A
        public String reverseWords(String s) {
            String[] str = s.split(" ");
            StringBuilder result = new StringBuilder();
            for(int i=0;   i<str.length;   i++){
                String temp = reverseWord(str[i]);
                //Append white spaces to all words except last 
                if(i==str.length-1)
                    result.append(temp);
                else
                    result.append(temp).append(" ");      
            }
            return result.toString();
        }
        //Function to reverse word
        public String reverseWord(String word){
            StringBuilder res = new StringBuilder(word);
            return res.reverse().toString();
        }
    }

Log in to reply
 

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