Accepted 4ms simple Java solution


  • 0
    C
    public class Solution {
    public String reverseWords(String s) {
        StringBuilder result=new StringBuilder();
        if(s.length()==0)
            return result.toString();
        String[] word=s.split(" ");
        //reverse the words and concatenate.
        for(int i=word.length-1; i>=0; i--) {
            if(word[i].length()>0)
                result.append(word[i]+' ');
        }
       //remove the space at the end.
        for(int j=result.length()-1; j>=0&&result.charAt(j)==' '; j--) {
            result.deleteCharAt(j);
        }
        return result.toString();
    }
    

    }


Log in to reply
 

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