0345. Reverse Vowels of a String

https://leetcode.com/problems/reverse-vowels-of-a-string

Description

Given a string s, reverse only all the vowels in the string and return it.

The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both cases.

Example 1:

**Input:** s = "hello"
**Output:** "holle"

Example 2:

**Input:** s = "leetcode"
**Output:** "leotcede"

Constraints:

  • 1 <= s.length <= 3 * 105

  • s consist of printable ASCII characters.

ac

class Solution {
    public String reverseVowels(String s) {
        // edge cases
        if (s.length() <= 1) return s;

        char[] chars = s.toCharArray();
        int l = 0, r = chars.length - 1;
        while (l < r) {
            while (l < r && !isVowel(chars[l])) l++;
            while (l < r && !isVowel(chars[r])) r--;
            char tmp = chars[l];
            chars[l++] = chars[r];
            chars[r--] = tmp;
        }

        return String.valueOf(chars);
    }

    private boolean isVowel(char c) {
        c = Character.toLowerCase(c);
        if (c == 'e' || c == 'u' || c == 'o' || c == 'i' || c == 'a')
            return true;
        return false;
    }
}

Last updated