题目描述

编写一个函数,以字符串作为输入,反转该字符串中的元音字母。

示例1

  1. 输入:"hello"
  2. 输出:"holle"

示例2

  1. 输入:"leetcode"
  2. 输出:"leotcede"

解题思路

还是采用双指针从两头往中间走,只是走的过程中需要判断下是否是元音字母,注意大写字母里的A E I O U也要算作元音,具体代码如下:

  1. class Solution {
  2. public:
  3. string reverseVowels(string s) {
  4. set<char> record{'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
  5. int i=0, j=s.length()-1;
  6. while (i<j) {
  7. while (i<s.length() && !record.count(s[i]))
  8. i++;
  9. while (j>=0 && !record.count(s[j]))
  10. j--;
  11. if (i>j)
  12. break;
  13. swap(s[i++], s[j--]);
  14. }
  15. return s;
  16. }
  17. };