leetCode题解之反转字符串中的元音字母

时间:2022-05-14 05:16:29

1、问题描述

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 中的元音字母位置反转,即第一个元音字母和最后一个元音字母交换位置。

,以此类推。

2、题目分析

题目和反转字符串很相似,只不过需要判断一个字符是否为元音字母。思路是两个指针一个从前往后遍历,遇到元音字母停下;另外一个从后往前遍历,遇到元音字母停下。然后交换位置。

3、代码

 string reverseVowels(string s) {

         string vow = "aeiouAEIOU";
int i ,j; for( i = ,j = s.size() - ; i < j ; )
{
if( vow.find( s[i]) != string::npos && vow.find( s[j] ) != string::npos )
swap(s[i],s[j]),i++,j--;
if(vow.find( s[i]) == string::npos )
i++;
if( vow.find(s[j]) == string::npos )
j--;
} return s; }