Title:Reverse Only Letters 917
Difficulty:Easy
原题leetcode地址: https://leetcode.com/problems/reverse-only-letters/
1. 双指针
时间复杂度:O(n),一次一层while循环。
空间复杂度:O(1),没有申请额外空间。
/**
* 双指针
* @param S
* @return
*/
public static String reverseOnlyLetters(String S) {
if (S.length() <= 0) {
return S;
}
char cs[] = S.toCharArray();
int start = 0;
int end = S.length() - 1;
while (start < end) {
if (Character.isLetter(cs[start]) && Character.isLetter(cs[end])) {
char c = cs[start];
cs[start] = cs[end];
cs[end] = c;
start++;
end--;
}
if (!Character.isLetter(cs[start])) {
start++;
}
if (!Character.isLetter(cs[end])) {
end--;
}
}
return new String(cs);
}