345. Reverse Vowels of a String

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

Example 1:

Given s = "hello", return "holle".

Example 2:

Given s = "leetcode", return "leotcede".

Note:

The vowels does not include the letter "y".

Thought

Consider the vowel in uppercase and lowercase.

Solution

public class Solution {
    public String reverseVowels(String s) {
        char[] chrs = s.toCharArray();
        int i = 0, j = chrs.length - 1;
        while (i < j) {
            if (isVowel(chrs[i]) && isVowel(chrs[j])) {
                char t = chrs[i];
                // remember moving the index after the exchange of values
                chrs[i++] = chrs[j];
                chrs[j--] = t;
            } else if (isVowel(chrs[i])) {
                j--;
            } else i++;
        }

        return String.valueOf(chrs);
    }

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

results matching ""

    No results matching ""