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;
        }
    };
  • 相关阅读:
    Java学习资源整理(超级全面)
    Java中的Iterable与Iterator详解
    git使用笔记1:结合Github远程仓库管理项目
    关于LeetCode上链表题目的一些trick
    关于链表中哨兵结点问题的深入剖析
    关于Java中基类构造器的调用问题
    大整数相乘问题总结以及Java实现
    快速排序实现及其pivot的选取
    阿里云服务器部署Java Web项目全过程
    Git 学习总结
  • 原文地址:https://www.cnblogs.com/fengziwei/p/7591353.html
Copyright © 2011-2022 走看看