Monday, June 19, 2017

557. Reverse Words in a String III

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Note: In the string, each word is separated by single space and there will not be any extra space in the string.



Solution:

Use two pointers.

One pointer points to the start of the substring that need to be reversed.

The other points to the end of the substring that need to be reversed.

Go through the input and find the pairs and reverse.

Then update the new pointer.



Code:


public class Solution {
    public String reverseWords(String s) {
        if (s == null || s.length() == 0) {
            return s;
        }
        char[] arr = s.toCharArray();
        int i = 0;
        int j = 0;
        while (j < s.length()) {
            while (j < s.length() && s.charAt(j) != ' ') {
                j++;
            }
            reverse(arr, i, j - 1);
            i = j + 1;
            j = i;
        }
        return new String(arr);
    }
    
    public void reverse(char[] arr, int i , int j) {
        while (i < j) {
            swap(arr, i++, j--);
        }
    }
    public void swap(char[] arr, int i, int j) {
        char tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }
}




public class Solution {
    public String reverseWords(String s) {
        if (s == null || s.length() == 0) {
            return s;
        }
        char[] arr = s.toCharArray();
        int start = 0;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == ' ') {
                reverse(arr, start, i - 1);
                start = i + 1;
            }
        }
        reverse(arr, start, arr.length - 1);
        return new String(arr);
    }
    
    public void reverse(char[] arr, int i , int j) {
        while (i < j) {
            swap(arr, i++, j--);
        }
    }
    public void swap(char[] arr, int i, int j) {
        char tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }
}