1
class Solution {
2
public String reverseOnlyLetters(String s) {
3
// converting the string to the charArray...
4
char[] ch = s.toCharArray();
5

6
int start = 0;
7
int end = s.length() - 1;
8

9
// Storing all the english alphabets in a hashmap so that the searching becomes easy...
10
HashMap<Character, Integer> hash = new HashMap<>();
11
for (int i = 0; i < 26; i++) {
12
hash.put((char) (97 + i), 1);
13
}
14
for (int i = 0; i < 26; i++) {
15
hash.put((char) (65 + i), 1);
16
}
17

18
// using two while loops ..since the constraints are too less thats why we can prefer nested
19
// loops approach..
20
while (start < end) {
21

22
// interating untill start pointer reacher a good character
23
while (start < end && !hash.containsKey(ch[start])) {
24
start++;
25
}
26
// iterating untill the end pointer reaches the good character..
27
while (end > start && !hash.containsKey(ch[end])) {
28
end--;
29
}
30

31
// swapping the array elements..
32
char temp = ch[start];
33
ch[start] = ch[end];
34
ch[end] = temp;
35

36
start++;
37
end--;
38
}
39

40
// converting the charArray to the string again..
41
String ans = new String(ch);
42
return ans;
43

44
// Time Complexity : O(N) (since the loops will run only till the number of charcters in the
45
// string..)
46
// Space Complexity : O(N) since we used hashmap..
47
}
48
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0