Short, clear Java solution


  • 0
    Y

    Construct a StringBuilder from the input, reverse it, convert back to String, split into an array on spaces, read the array into a string from back to front, return the string

    public class Solution {
        public String reverseWords(String s) {
    		String res = "";
    		String[] revSplit = new StringBuilder(s).reverse().toString().split(" ");
    		for (int i = revSplit.length - 1; i > 0; i--) {
    			res += revSplit[i] + " ";
    		}
    		return res + revSplit[0];
        }
    }
    

Log in to reply
 

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