Clean Java Solution


  • 0
    M

    In my solution I split the words, and then reverse them using a StringBuilder ( could have done reversing as a char array as well ), and accumulating the new Strings on another StringBuilder. Running time 18 ms.

    public class Solution {
        
        public String reverseWords(String s) {
            
            String[] words = s.split(" ");
            StringBuilder result = new StringBuilder();
            StringBuilder tmp = new StringBuilder();
            for (int i = 0; i < words.length; i++) {
                 tmp.setLength(0);
                 tmp.append(words[i]);
                 result.append(tmp.reverse().toString());
                 if (i != words.length -1) result.append(" ");
            }
            return result.toString();
        }
    }
    

Log in to reply
 

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