345. Reverse Vowels of a String

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

Subscribe to see which companies asked this question

 

反转字符串中的元音字符

 

第一种解法:

1. 保存原字符串s中,元音字符与对应的位置到两个数组vowels和pos

2. 反转vowels

3. 遍历vowels,将反转后的vowels[i]替换到原字符串s[pos[i]]

C++代码如下:

#include <string>
#include <algorithm>
#include <vector>


using namespace std;
class Solution {
public:
    bool isVowels(char c) {
        string vowels("aeiou");
        return vowels.end() != find(vowels.begin(), vowels.end(), tolower(c));
    }
    string reverseVowels(string s) {

        vector<char> vowels;
        vector<size_t> pos;
        for (string::iterator iter = s.begin(); iter != s.end(); iter++) {
            if (isVowels(*iter)) {
                vowels.push_back(*iter);
                pos.push_back(iter - s.begin());
            }
        }
        std::reverse(vowels.begin(), vowels.end());
        for (size_t i = 0; i < vowels.size(); i++) {
            s[pos[i]] = vowels[i];
        }
        return s;
    }
};

 第二种解法:分别中首部和尾部查找两个元音,然后替换即可

class Solution {
public:
    string reverseVowels(string s) {
        if (s.length() < 2) return s;
        string vowels="aeiouAEIOU";
        int i = 0, j = s.length()-1;

        while (i < j)
        {
            while (vowels.find(s[i])==string::npos && i<j) i++;
            while (vowels.find(s[j])==string::npos && i<j) j--;
            swap(s[i++],s[j--]);
        }
        return s;
    }
};

 

python版本

class Solution(object):
    def reverseVowels(self, s):
        """
        :type s: str
        :rtype: str
        """
        import re
        return re.sub('[aeiou]', '{}', s, flags=re.I).format(*re.findall('[aeiou]', s, flags=re.I)[::-1])

 

class Solution(object):
    def reverseVowels(self, s):
        """
        :type s: str
        :rtype: str
        """
        if not s.strip() or len(s) < 2:
            return s
        t = list(s)
        vowels = ['a','e','i','o','u','A','E','I','O','U']
        p1= 0
        p2= len(s)-1
        while p1 < p2:
            while s[p1] not in vowels and p1 < p2:
                p1+=1
            while s[p2] not in vowels and p1 < p2:
                p2-=1
            if p1 < p2:
                t[p1], t[p2] = t[p2], t[p1]
                p1+=1
                p2-=1
        return "".join(t)

 

 

 

 

 

 

 

 

 

posted @ 2016-05-16 21:50  godjob  Views(254)  Comments(0Edit  收藏  举报