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

要完成的函数:

string reverseVowels(string s) 

说明:

1、题目不难看懂,从字符串首部开始找,找到的第一个元音和,从字符串尾部开始找,找到的第一个元音交换位置。接着继续找第二个……直到所有元音都反转完成。

2、元音是“a”、“e“、“i”、“o”、“u”以及它们的大写形式。

3、令i=0,j=s.size()-1,不断查找并且交换位置,最终退出循环条件是i>=j。

代码如下:

    string reverseVowels(string s) 
    {
        int i=0,j=s.size()-1;
        while(i<j)
        {
            if(s[i]=='a'||s[i]=='e'||s[i]=='i'||s[i]=='o'||s[i]=='u'||s[i]=='A'||s[i]=='E'||s[i]=='I'||s[i]=='O'||s[i]=='U')
            {
                while(i<j)
                {
                    if(s[j]=='a'||s[j]=='e'||s[j]=='i'||s[j]=='o'||s[j]=='u'||s[j]=='A'||s[j]=='E'||s[j]=='I'||s[j]=='O'||s[j]=='U')
                    {
                        swap(s[i],s[j]);
                        j--;
                        break;
                    }
                    j--;
                }
            }
            i++;
        }
        return s;
    }

上述代码实测12ms,beats 86.45% of cpp submissions。

 

原文地址:https://www.cnblogs.com/chenjx85/p/8858837.html