• [LeetCode]345 Reverse Vowels of a String


     原题地址:

    https://leetcode.com/problems/reverse-vowels-of-a-string/description/

    题目:

    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".

    解法:

    我能想到的有两种解法:

    (1)

    先遍历一次字符串的每个字符,把元音字母的位置放在一个数组里面。然后按照数组将元音字母的位置交换即可。

    class Solution {
    public:
        string reverseVowels(string s) {
            vector<int> m;
          for (int i = 0; i < s.size(); i++) {
              if (s[i] == 'a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'o' || s[i] == 'u' || s[i] == 'A' || s[i] == 'E' || s[i] == 'I' || s[i] == 'O' || s[i] == 'U') {
                  m.push_back(i);
              }
          }
          if (m.size() == 0) return s;
          for (int i = 0; i <= (m.size() - 1) / 2; i++) {
              char temp = s[m[i]];
              s[m[i]] = s[m[m.size() - i - 1]];
              s[m[m.size() - i - 1]] = temp;
          }
          return s;
         }
    };

    (2)

    利用两个变量i和j,一加一减,遇到元音的位置就停下来,然后交换。我认为这种方法比较巧妙一点。类似于这种i和j变量的应用的题目,还有Intersection of Two Arrays II这道题,可以联系起来总计一下这种变量的使用。

    class Solution {
    public:
        bool isVowel(char c) {
            if (c == 'a' || c == 'A' ||
                c == 'e' || c == 'E' ||
                c == 'i' || c == 'I' ||
                c == 'o' || c == 'O' ||
                c == 'u' || c == 'U') return true;
            else return false;
        }
        string reverseVowels(string s) {
            int i = 0, j = s.size() - 1;
            while (i < j) {
                while (!isVowel(s[i]) && i < j) i++;
                while (!isVowel(s[j]) && i < j) j--;
                char temp = s[i];
                s[i] = s[j];
                s[j] = temp;
                i++;
                j--;
            } 
            return s;
        }
    };
  • 相关阅读:
    idea 中使用 svn
    [剑指offer] 40. 数组中只出现一次的数字
    [剑指offer] 39. 平衡二叉树
    [剑指offer] 38. 二叉树的深度
    [剑指offer] 37. 数字在排序数组中出现的次数
    [剑指offer] 36. 两个链表的第一个公共结点
    [剑指offer] 35. 数组中的逆序对
    vscode在win10 / linux下的.vscode文件夹的配置 (c++/c)
    [剑指offer] 34. 第一个只出现一次的字符
    [剑指offer] 33. 丑数
  • 原文地址:https://www.cnblogs.com/fengziwei/p/7591353.html
Copyright © 2020-2023  润新知