Short Java solution.


  • 1
    J
    public String reverseWords(String s) {
    	if (s.trim().isEmpty()) 
    		return s.trim();
    	StringBuffer ans = new StringBuffer();   	
        String[] words = s.trim().split("[ ]+");
        for (int i = words.length - 1; i >= 0; i--) {
        	ans.append(words[i]).append(" ");
        }
        return ans.toString().trim();
    }

Log in to reply
 

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