LeetCode 917 Reverse Only Letters
反轉字串,但只反轉字串中的字母,即a-z
,A-Z
。其他的字元保持原位。
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!"
解法
將字串轉為字元陣列,用兩個指標,從兩端向中間走, 依次找下一個字母進行交換,直到兩個指標相碰撞。
class Solution { public String reverseOnlyLetters(String S) { char[] chars = S.toCharArray(); int i = 0, j = chars.length - 1; while (i < j) { while (i < j && !isLetter(chars[i])) { i++; } while (i < j && !isLetter(chars[j])) { j--; } if (i < j) { char temp = chars[i]; chars[i] = chars[j]; chars[j] = temp; i++; j--; } } return new String(chars); } private boolean isLetter(char c) { return (c >= 65 && c <= 90) || (c >= 97 && c <= 122); } }
Runtime: 5 ms, faster than 93.93% of Java online submissions for Reverse Only Letters.