码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode题目:Reverse Vowels of a String

时间:2016-04-23 21:22:21      阅读:161      评论:0      收藏: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".

题目解答:

要求将字符串中所有的元音字母逆转,辅音字母的位置不受改变。

代码如下:

class Solution {
public:
    string reverseVowels(string s) {
        list<char> s_copy;
        list<char> s_vowels;
        int len = s.length();
        for(int i = 0;i < len;i++)
        {
            if(isVowel(s[i]))
            {
               s_vowels.push_back(s[i]);
               s_copy.push_back(‘a‘);
            }
            else
            {
                s_copy.push_back(s[i]);
            }
        }
        s_vowels.reverse();
        stringstream res;
        list<char>::iterator voit = s_vowels.begin();
        for(list<char>::iterator lit = s_copy.begin(); lit != s_copy.end();lit++)
        {
            if(*lit == ‘a‘)
            {
                res << *voit;
                voit++;
            }
            else
            {
                res << *lit;
            }
        }
        return res.str();
    }
   
    bool isVowel(char c)
    {
        switch(c)
        {
            case ‘a‘:
            case ‘e‘:
            case ‘i‘:
            case ‘o‘:
            case ‘u‘:
            case ‘A‘:
            case ‘E‘:
            case ‘I‘:
            case ‘O‘:
            case ‘U‘:
                return true;
            default:
                return false;
        }
    }
};

Leetcode题目:Reverse Vowels of a String

标签:

原文地址:http://www.cnblogs.com/CodingGirl121/p/5425411.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!