2021-03-28 LeetCode刷题 --345 反转字符串中的元音字母

2021-03-28 LeetCode刷题 --345 反转字符串中的元音字母

题目描述:编写一个函数,以字符串作为输入,反转该字符串中的元音字母。

下面是我写的:

class Solution {
    public String reverseVowels(String s) {
        char[] a=s.toCharArray();
        char c='a';
        HashSet<Character> yuan= new HashSet<>(
        Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'));
        int low=0;
        int high =a.length-1;
        while(low<=high){
            while(low<=a.length-1&&!yuan.contains(a[low])){
                low++;
            }
            while(high>=0&&!yuan.contains(a[high])){
                high--;
            }
            if(low<=high){
                c=a[low];
                a[low++]=a[high];
                a[high--]=c;
            }else{
                break;
            }

        }
        s=String.valueOf(a) ;
        return s;
    }
}

缺点:刚开始只会用ArrayList来建造集合,然后一个个的add进去,集合还不了解;
用的是字符串和字符数组的转换;
while里面的东西出错了好多次;

大神写的:

private final static HashSet<Character> vowels = new HashSet<>(
        Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'));

public String reverseVowels(String s) {
    if (s == null) return null;
    int i = 0, j = s.length() - 1;
    char[] result = new char[s.length()];
    while (i <= j) {
        char ci = s.charAt(i);
        char cj = s.charAt(j);
        if (!vowels.contains(ci)) {
            result[i++] = ci;
        } else if (!vowels.contains(cj)) {
            result[j--] = cj;
        } else {
            result[i++] = cj;
            result[j--] = ci;
        }
    }
    return new String(result);
}

有点:利用好了很多String的方法,如charAt();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值