Leetcode 345. Reverse Vowels of a String
Posted 琴影
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 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".
思路: 用一个hash表存一下元音字符, 然后设置左右指针找到两个都是元音的位置交换一下就可以了. 注意字符是大小写都有的.
1 class Solution { 2 public: 3 string reverseVowels(string s) { 4 set<char> hash{\'a\', \'e\', \'o\', \'i\', \'u\',\'A\', \'E\', \'I\', \'O\', \'U\'}; 5 int len = s.length(); 6 int left = 0, right = len - 1; 7 while(left < right){ 8 if(hash.count(s[left]) == 0) 9 left++; 10 if(hash.count(s[right]) == 0) 11 right--; 12 if(hash.count(s[left]) != 0 && hash.count(s[right]) != 0 ){ 13 swap(s[left], s[right]); 14 left++; 15 right--; 16 } 17 } 18 return s; 19 20 } 21 };
以上是关于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