File tree 1 file changed +45
-0
lines changed
1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ package easy ;
2
+
3
+ import java .util .HashSet ;
4
+ import java .util .Set ;
5
+
6
+ public class ReverseVowelsOfAString {
7
+ public String reverseVowels (String s ) {
8
+ StringBuilder sb = new StringBuilder (s );
9
+ Set <Character > vowels = new HashSet ();
10
+ vowels .add ('a' );
11
+ vowels .add ('e' );
12
+ vowels .add ('i' );
13
+ vowels .add ('o' );
14
+ vowels .add ('u' );
15
+ vowels .add ('A' );
16
+ vowels .add ('E' );
17
+ vowels .add ('I' );
18
+ vowels .add ('O' );
19
+ vowels .add ('U' );
20
+ //use two pointers approach would be the fastest
21
+ int i = 0 , j = s .length ()-1 ;
22
+ while (i < j ){
23
+ char left = s .charAt (i ), right = s .charAt (j );
24
+ while (i < j && !vowels .contains (left )){
25
+ i ++;
26
+ left = s .charAt (i );
27
+ }
28
+ while (i < j && !vowels .contains (right )){
29
+ j --;
30
+ right = s .charAt (j );
31
+ }
32
+ char temp = left ;
33
+ sb .setCharAt (i , right );
34
+ sb .setCharAt (j , temp );
35
+ i ++; j --;
36
+ }
37
+ return sb .toString ();
38
+ }
39
+
40
+ public static void main (String ...strings ){
41
+ ReverseVowelsOfAString test = new ReverseVowelsOfAString ();
42
+ String s = "leetcode" ;
43
+ System .out .println (test .reverseVowels (s ));
44
+ }
45
+ }
You can’t perform that action at this time.
0 commit comments