Reverse Vowels of a String

LeetCode Q 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”.

Solution

Solution : Two Pointers

Code:

public String reverseVowels(String s) {
	
	if  (s == null) return null;

	char[] chs = s.toCharArray();
	String vowels = "aeiouAEIOU";

	int left = 0, right = s.length() - 1;      
	
	while (left < right) {
		
		while (left < right && vowels.indexOf(chs[left]) == -1)
			left++;
		while (left < right && vowels.indexOf(chs[right]) == -1)
			right--;
		
		if (left < right) {
			char temp = chs[left];
			chs[left] = chs[right];
			chs[right] = temp;
		}
		
		left++; right--;
	}
	
	return String.valueOf(chs);
}

   Reprint policy


《Reverse Vowels of a String》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC