13 ms java solution


  • 0
    J
        public String reverseWords(String s) {
            StringBuilder sb = new StringBuilder();
            s = s.trim();
            for(int i = s.length() - 1, j = i + 1; i >= 0; i--){
                if(i == 0 || s.charAt(i) != ' ' && s.charAt(i-1) == ' ')
                    sb.append(s.substring(i, j)).append(' ');
                else if(s.charAt(i) == ' ') 
                    j = i;
            }
            return sb.length() > 0 ? sb.deleteCharAt(sb.length() - 1).toString() : "";
        }

Log in to reply
 

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