Question

Formatted question description: https://leetcode.ca/all/345.html

 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:

 Input: "hello"
 Output: "holle"

 Example 2:

 Input: "leetcode"
 Output: "leotcede"

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

 @tag-string

Algorithm

It should be noted that capital letters are counted, so there are ten letters in total.

We write a isVowel function to determine whether the current character is a vowel,

  • If both sides are vowels, then we exchange,
  • If the one on the left is not, move one place to the right,
  • If the one on the right is not, move one place to the left

Code

Java

public class Reverse_Vowels_of_a_String {

    class Solution {
        public String reverseVowels(String s) {
            char[] a = s.toCharArray();

            int l = 0; // left
            int r = a.length - 1; // right

            while (l < r) {
                if (isVowel(a[l]) && isVowel(a[r])) {
                    swap(a, l++, r--);
                } else if (isVowel(a[l])) {
                    r--;
                } else {
                    l++;
                }
            }

            return new String(a);
        }

        private boolean isVowel(char b) { // The letters A, E, I, O, and U are called vowels
            char c = Character.toLowerCase(b);
            return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
        }

        private void swap(char[] cs, int start, int end) {
            char temp = cs[start];
            cs[start] = cs[end];
            cs[end] = temp;
        }
    }
}

All Problems

All Solutions