Reverse Words in a String III

https://www.lintcode.com/problem/reverse-words-in-a-string-iii/description

public class Solution {
    /**
     * @param s: a string
     * @return: reverse the order of characters in each word within a sentence while still
     * preserving whitespace and initial word order
     */
    public String reverseWords(String s) {
        // Write your code here
        char[] chars = s.toCharArray();
        int left = 0;
        for (int i = 0; i < chars.length; i++) {
            char aChar = chars[i];
            if (aChar == ' ') {
                reverse(chars, left, i - 1);
                left = i + 1;
            }
        }
        reverse(chars, left, chars.length - 1);
        return new String(chars);
    }

    private void reverse(char[] chars, int left, int right) {
        while (left < right) {
            char c = chars[left];
            chars[left] = chars[right];
            chars[right] = c;
            left++;
            right--;
        }
    }
}

你可能感兴趣的:(Reverse Words in a String III)