[LC] 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.

 

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

Guess you like

Origin www.cnblogs.com/xuanlu/p/12132263.html