LeetCode 345. Reverse Vowels of a String
来源:互联网 发布:创意工作证设计软件 编辑:程序博客网 时间:2024/06/17 15:02
345. Reverse Vowels of a String
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”.
Note:
The vowels does not include the letter “y”.
Subscribe to see which companies asked this question.
题目内容:
题目要求给定一个字符串,将字符串里面的元音字母(’a’, ‘e’, ‘i’, ‘o’, ‘u’)倒序。
例如字符串”hello”中,’e’和’o’是元音字母,倒序之后原字符串变成’holle’。
解题思路:
首先因为题目中涉及到判断是否元音字母,所以我先把所有元音字母放到一个set里面,因为对于判断某个元素是否存在于一个集合里面,用set的效率会比vector这些容器要高。因为题目没有说明元音字母是大写还是小写,所以这里的set总共包含10个元素(’a’, ‘e’, ‘i’, ‘o’, ‘u’, ‘A’, ‘E’, ‘I’, ‘O’, ‘U’)。
接着用string::iterator开始从左到右遍历字符串,用string::reverse_iterator来做反向的遍历。字符串result用作保存最终经过元音字母倒序后的结果。从左到右遍历字符串的时候,如果遇到非元音字母,则直接把这个字符加到result后面,直到遇到第一个元音字母,则利用反向迭代器从后开始找到最后的一个元音字母,并把这个元音字母加到result后面,当遇到第二个元音字母,则继续利用反向迭代器找到倒数第二个元音字母,以此类推,直到原字符串所有字符都被遍历了一遍。
代码:
#include <iostream>#include <string>#include <set>using namespace std;class Solution {public: string reverseVowels(string s) { string result; string::iterator it = s.begin(); string::reverse_iterator rev_it = s.rbegin(); set<char> vowels; vowels.insert('a'); vowels.insert('e'); vowels.insert('i'); vowels.insert('o'); vowels.insert('u'); vowels.insert('A'); vowels.insert('E'); vowels.insert('I'); vowels.insert('O'); vowels.insert('U'); for(; it != s.end(); it++) { if(vowels.find(*it) != vowels.end()) { while(rev_it != s.rend()) { if(vowels.find(*rev_it) != vowels.end()) { result += *rev_it; rev_it++; break; } rev_it++; } } else { result += *it; } } return result; }};int main(int argc, const char * argv[]) { Solution sln; cout << sln.reverseVowels("hello") << endl; return 0;}
- 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
- LeetCode 345. Reverse Vowels of a String
- Leetcode 345. Reverse Vowels of a String
- LeetCode 345. Reverse Vowels of a String
- 345.[LeetCode]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
- [Leetcode]345. Reverse Vowels of a String
- Java高并发编程之第一阶段,多线程基础深入浅出
- 夜已芗阑,只实现了3列的数据排序(未完)
- 递归列出目录结构
- linux之网络和磁盘管理
- android之PULL解析XML(使用SSH框架服务端生成XML)
- LeetCode 345. Reverse Vowels of a String
- 数据库驱动程序
- uujdgylfyeiiksd
- Oracle Database 12.2 单实例的root.sh的变化--加入了安装TFA
- 关于java中this的用法
- acm练习 零起点学算法78——牛牛 2017 02 24
- Android JNI开发姿势 学习 AS2.0以下打so包、2.0以上解决 include jni.h报红
- Matlab 方括号“[ ]”的作用
- JAVA设计模式之单例模式