917. reverse only letters

Given a string S, return the “reversed” string where all characters that are not a letter stay in the same place, and all letters reverse their positions.

Example 1:

1
2
Input: "ab-cd"
Output: "dc-ba"

Example 2:

1
2
Input: "a-bC-dEf-ghIj"
Output: "j-Ih-gfE-dCba"

Example 3:

1
2
Input: "Test1ng-Leet=code-Q!"
Output: "Qedo1ct-eeLg=ntse-T!"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class  {
public String reverseOnlyLetters(String S) {
char[] chars = S.toCharArray();
int start = 0;
int end = chars.length - 1;
while (start < end) {
if (isLetter(chars[start]) && isLetter(chars[end])) {
char temp = chars[start];
chars[start] = chars[end];
chars[end] = temp;
start++;
end--;
continue;
}
if (isLetter(chars[start]) && !isLetter(chars[end])) {
end--;
continue;
}
if (!isLetter(chars[start]) && isLetter(chars[end])) {
start++;
continue;
}
if (!isLetter(chars[start]) && !isLetter(chars[end])) {
start++;
end--;
continue;
}
}
return new String(chars);
}
public boolean isLetter(char c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
}