Given a stringS, return the "reversed" string where all characters that are not a letter stay in the same place, and all letters reverse their positions.

没啥说的

class Solution {
    public String reverseOnlyLetters(String S) {
        char[] cs = S.toCharArray();
        int left = 0;
        int right = cs.length - 1;

        while(left < right) {
            while(left < right && !isLetter(cs[left]))
                left++;
            while(left < right && !isLetter(cs[right]))
                right--;
            swap(cs, left++, right--);
        }

        return String.valueOf(cs);
    }

    public boolean isLetter(char c) {
        return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
    }

    public void swap(char[] cs, int i, int j) {
        char temp = cs[i];
        cs[i] = cs[j];
        cs[j] = temp;
    }
}

results matching ""

    No results matching ""