反转字符串,但只反转字符串中的字母,即
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.