LeetCode 151.

Tags:

Complexity

  • Time complexity: O(n)

  • Space complexity: O(1)

Code

class Solution {
    public String reverseWords(String s) {
        int prev = -1;
        StringBuffer result = new StringBuffer();
        for (int i=s.length()-1; i>=0; i--) {
            if (prev < 0 && s.charAt(i) != ' ') {
                prev = i;
            }else if (prev > 0 && s.charAt(i) == ' ') {
                result.append(s.substring(i + 1, prev + 1)).append(" ");
                prev = -1;
            }
        }

        if (prev >= 0) result.append(s.substring(0, prev + 1));
        else result.deleteCharAt(result.length() - 1);

        return result.toString();
    }
}

Check out the description of this problem at LC 151.