345. Reverse Vowels of a String

本文介绍了一种使用双指针技术在字符串中反转元音字母的方法,通过将字符串转换为字符数组并利用集合判断元音,实现了高效地在字符串中反转元音字母的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Write a function that takes a string as input and reverse only the vowels of a string.

Example 1:
Input: “hello”
Output: “holle”

Example 2:
Input: “leetcode”
Output: “leotcede”

Note:
The vowels does not include the letter “y”.

解法

用双指针的头尾指针方法,一个指针从头开始遍历,一个指针从末尾开始遍历直到两个指针遇见则遍历完。这个题还要处理的是一开始将string转成list,因为string不能赋值,最后再用"’’.join(s)转回string

python

class Solution:
    def reverseVowels(self, s: str) -> str:
        i=0
        s=list(s)
        j=len(s)-1
        vowel=set(list('aieouAEIOU'))
        while(i<j):
            if(s[i] in vowel and s[j] in vowel):
                s[i],s[j]=s[j],s[i]
                i=i+1
                j=j-1
            if(s[i] not in vowel):
                i=i+1
            if(s[j] not in vowel):
                j=j-1
        return ''.join(s)

java
需要用到java string 的contains方法,需要把string转换为charArray

class Solution {
    public String reverseVowels(String s) {
        int i=0,j=s.length()-1;
        String vowels = "aeiouAEIOU";
        char[] chars = s.toCharArray();
        while(i<j){
            if(vowels.contains(chars[i]+"")&&vowels.contains(chars[j]+"")){
                char tmp=chars[i];
                chars[i]=chars[j];
                chars[j]=tmp;
                i++;
                j--;
            }
            else if(!vowels.contains(chars[i]+"")){
                i++;
            }
            else if(!vowels.contains(chars[j]+"")){
                j--;
            }
        }
        return new String(chars);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值