导航

LeetCode 345. Reverse Vowels of a String

Posted on 2016-09-20 22:39  CSU蛋李  阅读(171)  评论(0编辑  收藏  举报

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

题目要求:将一个字符串中的元音字母前后调换,设置两个位置,如果两个位置的都是元音字母就调换即可

 

class Solution {
public:
    string reverseVowels(string s) {
        char temp = ' ';
        string Vowels("aAeEiIoOuU");
        int start = 0, end = s.size() - 1;
        while (start<end)
        {
            if (Vowels.find(s[start]) != string::npos&&Vowels.find(s[end]) != string::npos)
            {
                temp = s[start];
                s[start] = s[end];
                s[end] = temp;
                ++start;
                --end;
            }else 
            {
                if (Vowels.find(s[start]) == string::npos && Vowels.find(s[end]) == string::npos)
                {
                    ++start;
                    --end;
                    continue;
                }
                if (Vowels.find(s[start] == string::npos) && Vowels.find(s[end]) != string::npos)
                {
                    ++start;
                }
                else
                {
                    --end;
                }
            }
        }
        return s;
    }
};