zoukankan      html  css  js  c++  java
  • [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;
        }
    };
  • 相关阅读:
    二十一、正则表达式
    二十、冒泡算法,递归,装饰器
    十九、python内置函数汇总
    Jenkins-[--4--]-浏览器不能打开jenkins报告,报错Opening Robot Framework report failed
    Jenkins-[--3--]-robotframework脚本,配置自动发送邮件
    Jenkins-[--2--]-执行本地的robotframework项目
    Jenkins-[--1--]-环境配置
    Redis常用数据类型介绍、使用场景及其操作命令
    angular过滤器
    jscode属性排序
  • 原文地址:https://www.cnblogs.com/fengziwei/p/7591353.html
Copyright © 2011-2022 走看看