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);
}
标签:String,chars,Example,while,easy,Output,Input,917,leetcode
From: https://www.cnblogs.com/iyiluo/p/16936835.html