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

NOTICE THAT left cannot go beyond right, otherwise you end up swap already swapped pairs.

public class Solution {
    public String reverseVowels(String s) {
        char[] d = s.toCharArray();
        String dict = "aeiouAEIOU";

        int left = 0;
        int right = d.length-1;
        while(left < right){
            while(left < d.length && dict.indexOf(d[left]) == -1) left++;
            if(left >= d.length || left >= right) break;
            while(right >= 0 && dict.indexOf(d[right]) == -1) right--;
            if(right < 0 || right <= left) break;

            char tmp = d[left];
            d[left] = d[right];
            d[right] = tmp;
            left++;
            right--;
        }

        return new String(d);
    }
}

results matching ""

    No results matching ""