917. Reverse Only Letters

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

 

Example 1:

Input: "ab-cd"
Output: "dc-ba"

Example 2:

Input: "a-bC-dEf-ghIj"
Output: "j-Ih-gfE-dCba"

Example 3:

Input: "Test1ng-Leet=code-Q!"
Output: "Qedo1ct-eeLg=ntse-T!"

Note:

  1. S.length <= 100
  2. 33 <= S[i].ASCIIcode <= 122 
  3. S doesn't contain  or "

two pointers

time: O(n), space: O(1)

class Solution {
    public String reverseOnlyLetters(String S) {
        char[] str = S.toCharArray();
        int i = 0, j = str.length - 1;
        while(i < j) {
            if(Character.isLetter(str[i]) && Character.isLetter(str[j])) {
                swap(str, i++, j--);
            } else if(Character.isLetter(str[i])) {
                j--;
            } else if(Character.isLetter(str[j])) {
                i++;
            } else {
                i++;
                j--;
            }
        }
        return new String(str);
    }
    
    private void swap(char[] arr, int i, int j) {
        char tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }
}
原文地址:https://www.cnblogs.com/fatttcat/p/11340658.html