[LeetCode] 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".

Note:
The vowels does not include the letter "y".

利用两个指针来遍历字符串数组s,遍历时判断符合条件的字母交换即可

class Solution {
public:
    string reverseVowels(string s) {
        unordered_set<char> vowels = {'A', 'a', 'E', 'e', 'I', 'i', 'O', 'o', 'U', 'u'};
        int left = 0, right = s.size() - 1;
        while (left <= right) {
            if (vowels.count(s[left]) == 0)
                left++;
            else if (vowels.count(s[right]) == 0)
                right--;
            else
                swap(s[left++], s[right--]);
        }
        return s;
    }
};
// 22 ms

 

posted @ 2017-08-29 15:11  immjc  阅读(129)  评论(0编辑  收藏  举报