LeetCode_345. Reverse Vowels of a String

Posted 邓戈麟

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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"));
	}
}

 

以上是关于LeetCode_345. Reverse Vowels of a String的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode.345 | Reverse Vowels of a String

LeetCode #345 Reverse Vowels of a String

LeetCode 345. Reverse Vowels of a String

Leetcode 345. Reverse Vowels of a String

[LeetCode]345 Reverse Vowels of a String

leetcode 345. Reverse Vowels of a String