345. Reverse Vowels of a String

Link

Write a function that takes a string as input and reverse only the vowels of a string.

Example 1:

Input: "hello"
Output: "holle"

Example 2:

Input: "leetcode"
Output: "leotcede"

Note: The vowels does not include the letter "y".

Solution

class Solution {
    public String reverseVowels(String s) {
        char[] chars = s.toCharArray();
        int n = chars.length;
        int i = 0, j = n - 1;
        while(i < j){
            while( i < n && !isVowels(chars[i])) i++;
            while( i < j && !isVowels(chars[j])) j--;
            if( i < n && i < j){
                char temp = chars[i];
                chars[i] = chars[j];
                chars[j] = temp;
                i++;
                j--;
            }
            
        }
        return new String(chars);
    }
    
    public boolean isVowels(char c){
        if( c == 'a'||c == 'i'||c == 'e'|| c == 'o'|| c == 'u'
          || c == 'A'||c == 'I'||c == 'E'|| c == 'O'|| c == 'U')
        {
            return true;
        }
        return false;
    }
}

Last updated

Was this helpful?