Topic
- Two Pointers
- String
Description
https://leetcode.com/problems/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”.
Analysis
略
Submission
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class ReverseVowelsOfAString {
private static final Set<Character> VOWELS = //
new HashSet<>(Arrays.asList('A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u'));
public String reverseVowels(String s) {
if (s == null || s.length() == 0)
return s;
char[] array = s.toCharArray();
int left = 0, right = array.length - 1;
while (left < right) {
while (left < right && !VOWELS.contains(array[left]))
left++;
while (left < right && !VOWELS.contains(array[right]))
right--;
char temp = array[left];
array[left++] = array[right];
array[right--] = temp;
}
return new String(array);
}
}
Test
import static org.junit.Assert.*;
import org.junit.Test;
public class ReverseVowelsOfAStringTest {
@Test
public void test() {
ReverseVowelsOfAString obj = new ReverseVowelsOfAString();
assertEquals("holle", obj.reverseVowels("hello"));
assertEquals("leotcede", obj.reverseVowels("leetcode"));
}
}