跳至主要內容

345. 反转字符串中的元音字母


345. 反转字符串中的元音字母open in new window

🟢   🔖  双指针 字符串  🔗 力扣open 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反转字符串open in new window[✓]双指针 字符串
1119删去字符串中的元音 🔒open in new window字符串
2785将字符串中的元音字母排序open in new window字符串 排序
2810故障键盘open in new window字符串 模拟