File tree 1 file changed +10
-9
lines changed
scripts/algorithms/R/Reverse Only Letters
1 file changed +10
-9
lines changed Original file line number Diff line number Diff line change
1
+ // Runtime: 1 ms (Top 90.35%) | Memory: 40.8 MB (Top 87.29%)
1
2
class Solution {
2
3
public String reverseOnlyLetters (String s ) {
3
4
// converting the string to the charArray...
4
5
char [] ch = s .toCharArray ();
5
-
6
+
6
7
int start = 0 ;
7
8
int end = s .length ()-1 ;
8
-
9
+
9
10
// Storing all the english alphabets in a hashmap so that the searching becomes easy...
10
11
HashMap <Character , Integer > hash = new HashMap <>();
11
12
for (int i =0 ; i <26 ;i ++){
@@ -14,10 +15,10 @@ public String reverseOnlyLetters(String s) {
14
15
for (int i =0 ; i <26 ; i ++){
15
16
hash .put ((char )(65 +i ) , 1 );
16
17
}
17
-
18
+
18
19
// using two while loops ..since the constraints are too less thats why we can prefer nested loops approach..
19
20
while (start <end ){
20
-
21
+
21
22
// interating untill start pointer reacher a good character
22
23
while (start <end &&!hash .containsKey (ch [start ])){
23
24
start ++;
@@ -26,21 +27,21 @@ public String reverseOnlyLetters(String s) {
26
27
while (end >start &&!hash .containsKey (ch [end ])){
27
28
end --;
28
29
}
29
-
30
+
30
31
// swapping the array elements..
31
32
char temp = ch [start ];
32
33
ch [start ] = ch [end ];
33
34
ch [end ] = temp ;
34
-
35
+
35
36
start ++;
36
37
end --;
37
38
}
38
-
39
+
39
40
// converting the charArray to the string again..
40
41
String ans = new String (ch );
41
42
return ans ;
42
-
43
+
43
44
// Time Complexity : O(N) (since the loops will run only till the number of charcters in the string..)
44
45
// Space Complexity : O(N) since we used hashmap..
45
46
}
46
- }
47
+ }
You can’t perform that action at this time.
0 commit comments