Created
August 3, 2023 08:49
-
-
Save ritik-agrawal/f94e06b9a5e35abe2bcfa22a4da10ee5 to your computer and use it in GitHub Desktop.
Leetcode: Reverse vowels in the given string.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public String reverseVowels(String s) { | |
var arr = s.toCharArray(); | |
var l = 0; | |
var r = arr.length - 1; | |
while (l < r && l < arr.length && r >= 0 ){ | |
while (l < arr.length && l < r && !isVowel(arr[l])){ | |
l++; | |
} | |
while (r >= 0 && l < r && !isVowel(arr[r])){ | |
r--; | |
} | |
if (l >= r){ | |
break; | |
} | |
var temp = arr[l]; | |
arr[l] = arr[r]; | |
arr[r] = temp; | |
l++; | |
r--; | |
} | |
var sb = new StringBuilder(); | |
sb.append(arr); | |
return sb.toString(); | |
} | |
private boolean isVowel(char c){ | |
return ( | |
c == 'a' || c == 'A' || | |
c == 'e' || c == 'E' || | |
c == 'i' || c == 'I' || | |
c == 'o' || c == 'O' || | |
c == 'u' || c == 'U' | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Observation
The above code has been implemented by me. The method isVowel is different from the initial implementation. The first implementation is as follows:
The code with the above implementation of the isVowel method took 7 ms of runtime whereas the implementation mentioned above took 2 ms.