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:
S.length <= 100
33 <= S[i].ASCIIcode <= 122
S
doesn't containor
"
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; } }