345. Reverse Vowels of a String

来源:互联网 发布:简约个人业务源码 编辑:程序博客网 时间:2024/05/23 11:24

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) {        int i=0;        int 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')            {                i++;            }else 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')            {                j--;            }else            {                int tmp = s[i];                s[i] = s[j];                s[j] = tmp;                i++;                j--;            }        }        return s;    }};
0 0