跳至主要內容

345. Reverse Vowels of a String


345. Reverse Vowels of a Stringopen in new window

🟢   🔖  双指针 字符串  🔗 LeetCodeopen in new window

题目

Given a string s, reverse only all the vowels in the string and return it.

The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both lower and upper cases, more than once.

Example 1:

Input: s = "hello"

Output: "holle"

Example 2:

Input: s = "leetcode"

Output: "leotcede"

Constraints:

  • 1 <= s.length <= 3 * 105
  • s consist of printable ASCII characters.

题目大意

题目要求我们反转字符串中的元音字母。需要注意字母大小写。

解题思路

这一题的解题思路是用 2 个指针,指针对撞的思路,来不断交换首尾元素,即可。这一题和 第 344 题 思路一样。

代码

/**
 * @param {string} s
 * @return {string}
 */
var reverseVowels = function (s) {
	s = s.split('');
	let left = 0;
	let right = s.length - 1;
	while (left < right) {
		if (!isVowel(s[left])) {
			left++;
		} else if (!isVowel(s[right])) {
			right--;
		} else {
			let temp = s[left];
			s[left] = s[right];
			s[right] = temp;
			left++;
			right--;
		}
	}
	return s.join('');
};

var isVowel = function (i) {
	i = i.toLowerCase();
	return i == 'a' || i == 'e' || i == 'i' || i == 'o' || i == 'u';
};

相关题目

相关题目
- [344. 反转字符串](./0344.md)
- [🔒 Remove Vowels from a String](https://leetcode.com/problems/remove-vowels-from-a-string)
- [2810. Faulty Keyboard](https://leetcode.com/problems/faulty-keyboard)
- [2785. Sort Vowels in a String](https://leetcode.com/problems/sort-vowels-in-a-string)