zoukankan      html  css  js  c++  java
  • 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. 反思

  • 相关阅读:
    省常中模拟 Test4
    省常中模拟 Test3 Day1
    省常中模拟 Test3 Day2
    省常中模拟 Test1 Day1
    树型动态规划练习总结
    noip2010提高组题解
    noip2003提高组题解
    noip2009提高组题解
    noip2004提高组题解
    noip2002提高组题解
  • 原文地址:https://www.cnblogs.com/whl2012/p/5820065.html
Copyright © 2011-2022 走看看