LeetCode_345. Reverse Vowels of a String

 

345. Reverse Vowels of a String

Easy

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

 

package leetcode.easy;

public class ReverseVowelsOfAString {
	private static final boolean[] isVowel;

	static {
		isVowel = new boolean[123]; // 'z' is 122
		isVowel['a'] = true;
		isVowel['e'] = true;
		isVowel['i'] = true;
		isVowel['o'] = true;
		isVowel['u'] = true;

		isVowel['A'] = true;
		isVowel['E'] = true;
		isVowel['I'] = true;
		isVowel['O'] = true;
		isVowel['U'] = true;
	}

	public String reverseVowels(String s) {
		char[] ch = s.toCharArray();
		int i = 0;
		int j = s.length() - 1;
		while (i < j) {
			if (!isVowel[ch[i]]) {
				i++;
			} else if (!isVowel[ch[j]]) {
				j--;
			} else {
				char c = ch[i];
				ch[i] = ch[j];
				ch[j] = c;
				i++;
				j--;
			}
		}
		return new String(ch);
	}

	@org.junit.Test
	public void test() {
		System.out.println(reverseVowels("hello"));
		System.out.println(reverseVowels("leetcode"));
	}
}

 

Guess you like

Origin www.cnblogs.com/denggelin/p/11832588.html