【每日一题DAY24】LC1704判断字符串的两半是否相似|双指针 模拟

57 篇文章 0 订阅
23 篇文章 0 订阅

判断字符串的两半是否相似【LC1704】

You are given a string s of even length. Split this string into two halves of equal lengths, and let a be the first half and b be the second half.

Two strings are alike if they have the same number of vowels ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'). Notice that s contains uppercase and lowercase letters.

Return true if a and b are alike. Otherwise, return false.

给你一个偶数长度的字符串 s 。将其拆分成长度相同的两半,前一半为 a ,后一半为 b

两个字符串 相似 的前提是它们都含有相同数目的元音('a''e''i''o''u''A''E''I''O''U')。注意,s 可能同时含有大写和小写字母。

如果 ab 相似,返回 true ;否则,返回 false

1111 怎么在草稿里没有发出去 泪目

  • 思路:使用双指针统计字符串a和字符串b中元音字母的个数,个数相同则返回true

  • 实现

    class Solution {
        public boolean halvesAreAlike(String s) {
            int left = 0;
            int right = s.length()-1;
            int a = 0;
            int b = 0;
            while (left < right){
                if (isVowels(s.charAt(left))){
                    a++;
                }
                if (isVowels(s.charAt(right))){
                    b++;
                }
                left++;
                right--;
            }
            return a == b;
        }
        public boolean isVowels(char c){
            if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ){
                return true;
            }
            if (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U' ){
                return true;
            }
            return false;
        }
    }
    
  • 复杂度

    • 时间复杂度: O ( n ) O(n) O(n),n为两个字符串的最大长度
    • 空间复杂度: O ( 1 ) O(1) O(1)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值