[LeetCode] Reverse Vowels of a String 翻转字符串中的元音字母
LeetCode string 字符串 of 字母 翻转 reverse 元音
2023-09-11 14:21:37 时间
Write a function that takes a string as input and reverse only the vowels of a string.
Example 1:
Given s = "hello", return "holle".
Example 2:
Given s = "leetcode", return "leotcede".
这道题让我们翻转字符串中的元音字母,元音字母有五个a,e,i,o,u,需要注意的是大写的也算,所以总共有十个字母。我们写一个isVowel的函数来判断当前字符是否为元音字母,如果两边都是元音字母,那么我们交换,如果左边的不是,向右移动一位,如果右边的不是,则向左移动一位,参见代码如下:
解法一:
class Solution { public: string reverseVowels(string s) { int left = 0, right= s.size() - 1; while (left < right) { if (isVowel(s[left]) && isVowel(s[right])) { swap(s[left++], s[right--]); } else if (isVowel(s[left])) { --right; } else { ++left; } } return s; } bool isVowel(char c) { return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U'; } };
或者我们也可以用自带函数find_first_of和find_last_of来找出包含给定字符串中任意一个字符的下一个位置进行交换即可:
解法二:
class Solution { public: string reverseVowels(string s) { int left = 0, right = s.size() - 1; while (left < right) { left = s.find_first_of("aeiouAEIOU", left); right = s.find_last_of("aeiouAEIOU", right); if (left < right) { swap(s[left++], s[right--]); } } return s; } };
我们也可以把元音字母都存在一个字符串里,然后每遇到一个字符,就到元音字符串里去找,如果存在就说明当前字符是元音字符,参见代码如下:
解法三:
class Solution { public: string reverseVowels(string s) { int left = 0, right = s.size() - 1; string t = "aeiouAEIOU"; while (left < right) { if (t.find(s[left]) == string::npos) ++left; else if (t.find(s[right]) == string::npos) --right; else swap(s[left++], s[right--]); } return s; } };
类似题目:
参考资料:
https://leetcode.com/discuss/99048/easy-to-understand-c-solution
https://leetcode.com/discuss/99047/super-clean-solution-using-find_first_of-and-find_last_of
https://leetcode.com/discuss/99062/java-two-pointers-solution-easy-understand-finish-interview
相关文章
- Java实现 LeetCode 762 二进制表示中质数个计算置位(位运算+JDK的方法)
- Java实现 LeetCode 587 安装栅栏(图算法转换成数学问题)
- Java实现 LeetCode 477 汉明距离总和
- Java实现 LeetCode 349 两个数组的交集
- Java实现 LeetCode 278 第一个错误的版本
- Java实现 LeetCode 211 添加与搜索单词 - 数据结构设计
- Java实现 LeetCode 49 字母异位词分组
- (LeetCode 83)Remove Duplicates from Sorted Lists
- 【RF库测试】Encode String To Bytes&Decode Bytes To String& should be string&should be unicode string &should not be string
- [LeetCode] Reverse Words in a String
- LeetCode-396. 旋转函数【动态规划,思路清晰,错位相减法,迭代】
- Atitit 命令行dsl传递参数的几种模式对比 cli url模式 键值对NameValuePair urlutil String string = " -host 101.13
- 【LeetCode 34】在排序数组中查找元素的第一个和最后一个位置
- LeetCode【8】. String to Integer (atoi) --java实现
- [LeetCode] 42. 接雨水 ☆☆☆☆☆(按列、动态规划、双指针)
- leetcode 1.两数之和 js 实现
- [LeetCode]Maximum Product Subarray
- leetcode 557. Reverse Words in a String III
- 【Mac系统】Vscode使用LeetCode插件报错‘leetcode.toggleLeetCodeCn‘ not found
- 【Leetcode刷题Python】322. 零钱兑换