345. Reverse Vowels of a String

1. 问题描述

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".
Tags: Two Pointers String
Similar: Problems (E) Reverse String

2. 解题思路


3. 代码

class Solution {
public:
    string reverseVowels(string s) 
    {
        string::size_type iLeft = -1;
        string::size_type iRight = s.size();
        while (true)
        {
            iLeft = FindVowels(s, iLeft+1);
            iRight = rFindVowels(s, iRight-1);
            if (iLeft < iRight && iLeft != s.npos && iRight != s.npos)
            {
                char ch = s[iLeft];
                s[iLeft] = s[iRight];
                s[iRight] = ch;
            }
            else
            {
                break;
            }
        }
        return s;
    }
    
private:
    int FindVowels(const string &s, int iStartPos)
    {
        string strVowels = "aAoOeEiIuU";
        string::size_type pos = s.find_first_of(strVowels, iStartPos);
        return pos;
    }

    int rFindVowels(const string &s, int iStartPos)
    {
        string strVowels = "aAoOeEiIuU";
        string::size_type pos = s.find_last_of(strVowels, iStartPos);
        return pos;
    }
};

4. 反思

原文地址:https://www.cnblogs.com/whl2012/p/5820065.html