-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseOnlyLetters.java
More file actions
32 lines (27 loc) · 939 Bytes
/
Copy pathReverseOnlyLetters.java
File metadata and controls
32 lines (27 loc) · 939 Bytes
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
package LeetcodePractice;
public class ReverseOnlyLetters {
public static void main(String[] args) {
System.out.println(reverseOnlyLetters("ab-cd"));
System.out.println(reverseOnlyLetters("a-bC-dEf-ghIj"));
System.out.println(reverseOnlyLetters("Test1ng-Leet=code-Q!"));
}
public static String reverseOnlyLetters(String s) {
char[] chars = s.toCharArray();
int left = 0, right = chars.length - 1;
while (left < right) {
if (!Character.isLetter(chars[left])) {
left++;
} else if (!Character.isLetter(chars[right])) {
right--;
} else {
// Swap letters
char temp = chars[left];
chars[left] = chars[right];
chars[right] = temp;
left++;
right--;
}
}
return new String(chars);
}
}