557. 反转字符串中的单词 III

class Solution {
    public String reverseWords(String s) {
        char[] cs = s.toCharArray();

        int left = 0;
        int right = s.indexOf(" ", left);

        while (left < right) {
            int now = right;

            while (left < right - 1) {
                cs[left] = (char)(cs[left] ^ cs[right - 1]);
                cs[right - 1] = (char)(cs[left] ^ cs[right - 1]);
                cs[left] = (char)(cs[left] ^ cs[right - 1]);
                left++;
                right--;
            }

            left = now + 1;
            right = s.indexOf(" ", left);
        }

        right = cs.length - 1;

        while (left < right) {
            cs[left] = (char)(cs[left] ^ cs[right]);
            cs[right] = (char)(cs[left] ^ cs[right]);
            cs[left] = (char)(cs[left] ^ cs[right]);
            left++;
            right--;
        }

        return new String(cs);
    }
}
557. 反转字符串中的单词 III_第1张图片
image.png

你可能感兴趣的:(557. 反转字符串中的单词 III)