My Java Solution


  • 0
    C
    public class Solution {
        public String reverseWords(String s) {
            StringBuilder sb = new StringBuilder();
            int i = s.length() - 1, j = i;
            while (i >= 0) {
                while (j >= 0 && s.charAt(j) != ' ') j--;
                sb.append(s.substring(j+1, i+1));
                if (i > j) sb.append(" ");
                j--;
                i = j;
            }
            if(sb.length() > 0) sb.deleteCharAt(sb.length() - 1);
            return sb.toString();
        }
    }
    

Log in to reply
 

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