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".

Solution

public class Solution {
       public String reverseVowels(String s) {
        if (s == null || s.length() == 0) {
            return s;
        }

        StringBuffer sb = new StringBuffer(s);
        StringBuffer vowles = new StringBuffer();
        List<Integer> positions = new ArrayList<>();

        for (int i = 0; i < s.length(); i++) {
            if ("AIUEOaiueo".contains(s.substring(i, i + 1))) {
                vowles.append(s.charAt(i));
                positions.add(i);
            }
        }

        StringBuffer reverse = vowles.reverse();
        for (int i = 0; i < positions.size(); i++) {
            sb.setCharAt(positions.get(i), reverse.charAt(i));
        }

        return sb.toString();
    }
}

results matching ""

    No results matching ""