[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;
    }
};

 

posted @ 2017-09-25 12:50  fengzw  阅读(157)  评论(0编辑  收藏  举报