public String reverseWords(String s) {
        s = s.trim();
        if(s.isEmpty()) return s;

        StringBuilder result = new StringBuilder();
        int index = s.length() - 1;
        while(index >= 0){
            int end = index;
            while(index >= 0 && s.charAt(index) != ' ') index--;
            result.append(s.substring(index + 1, end + 1));
            if(index >= 0 ) result.append(" ");
            while(index >= 0 && s.charAt(index) == ' ') index--;
        }
        return result.toString();
    }