LeetCode 75
Reverse Vowels of a String
- Problem
- LC 345
- File
- official75_LC345ReverseVowelsOfAString.java
- Path
- pkg5leetcode/official75/official75_LC345ReverseVowelsOfAString.java
- Package
- pkg5leetcode.official75
- Command
- java pkg5leetcode/official75/official75_LC345ReverseVowelsOfAString.java
- Approach
- Two pointers swap vowels from both ends.
- Complexity
- Time O(n), Space O(n)
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg5leetcode.official75;2 3/*4 * Reverse Vowels of a String | LC 3455 * APPROACH: Two pointers swap vowels from both ends.6 * COMPLEXITY: Time O(n), Space O(n)7 */8public class official75_LC345ReverseVowelsOfAString {9 static boolean isVowel(char c) {10 c = Character.toLowerCase(c);11 return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';12 }13 14 static String reverseVowels(String s) {15 char[] a = s.toCharArray();16 int l = 0, r = a.length - 1;17 while (l < r) {18 while (l < r && !isVowel(a[l])) l++;19 while (l < r && !isVowel(a[r])) r--;20 char t = a[l]; a[l] = a[r]; a[r] = t;21 l++; r--;22 }23 return new String(a);24 }25 26 public static void main(String[] args) {27 check("AceCreIm".equals(reverseVowels("IceCreAm")), "case1");28 check("leotcede".equals(reverseVowels("leetcode")), "case2");29 System.out.println("all tests passed");30 }31 32 static void check(boolean cond, String name) {33 if (!cond) throw new AssertionError("FAILED: " + name);34 System.out.println(" PASS " + name);35 }36}