Skip to content

Instantly share code, notes, and snippets.

@ritik-agrawal
Created August 3, 2023 08:49
Show Gist options
  • Save ritik-agrawal/f94e06b9a5e35abe2bcfa22a4da10ee5 to your computer and use it in GitHub Desktop.
Save ritik-agrawal/f94e06b9a5e35abe2bcfa22a4da10ee5 to your computer and use it in GitHub Desktop.
Leetcode: Reverse vowels in the given string.
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'
);
}
}
@ritik-agrawal
Copy link
Author

Observation

The above code has been implemented by me. The method isVowel is different from the initial implementation. The first implementation is as follows:

private boolean isVowel(char c){
        return (
            Objects.equals(c, 'a') || Objects.equals(c, 'A') ||
            Objects.equals(c, 'e') || Objects.equals(c, 'E') ||
            Objects.equals(c, 'i') || Objects.equals(c, 'I') ||
            Objects.equals(c, 'o') || Objects.equals(c, 'O') || 
            Objects.equals(c, 'u') || Objects.equals(c, 'U')  
        );
    }

The code with the above implementation of the isVowel method took 7 ms of runtime whereas the implementation mentioned above took 2 ms.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment