leetcode-917-easy
阿新 • • 發佈:2022-11-30
Reverse Only Letters
Given a string s, reverse the string according to the following rules: All the characters that are not English letters remain in the same position. All the English letters (lowercase or uppercase) should be reversed. Return s after reversing it. Example 1: Input: s = "ab-cd" Output: "dc-ba" Example 2: Input: s = "a-bC-dEf-ghIj" Output: "j-Ih-gfE-dCba" Example 3: Input: s = "Test1ng-Leet=code-Q!" Output: "Qedo1ct-eeLg=ntse-T!" Constraints: 1 <= s.length <= 100 s consists of characters with ASCII values in the range [33, 122]. s does not contain '\"' or '\\'.
思路一:雙指標,先定位兩個指標的位置,然後交換合法的字元
public String reverseOnlyLetters(String s) { char[] chars = s.toCharArray(); int i = 0; int j = chars.length - 1; while (true) { while (i < chars.length && !Character.isLetter(chars[i])) { i++; } while (j >= 0 && !Character.isLetter(chars[j])) { j--; } if (i < j) { char t = chars[i]; chars[i] = chars[j]; chars[j] = t; } else { break; } i++; j--; } return new String(chars); }