557. Reverse Words in a String III

Description

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

class Solution {
    public String reverseWords(String s) {
        int i = 0;
        int n = s.length();
        char[] arr = s.toCharArray();
        
        while (i < n) {
            // skip spaces
            while (i < n && arr[i] == ' ') {
                ++i;
            }
            
            int wordStart = i;
            // find the end of current word
            while (i < n && arr[i] != ' ') {
                ++i;
            }
            
            reverse(arr, wordStart, i - 1);
        }
        
        return new String(arr);
    }
    
    public void reverse(char[] chars, int start, int end) {
        while (start < end) {
            swap(chars, start++, end--);
        }
    }
    
    public void swap(char[] chars, int i, int j) {
        char tmp = chars[i];
        chars[i] = chars[j];
        chars[j] = tmp;
    }
}

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