有效的回文构词法(Java)

该博客探讨了如何使用Java有效地判断一个字符串是否为另一个字符串的回文词。提供了两种解决方案,包括使用数组和HashMap,分别分析了它们的时间复杂度。

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

题目描述

给定两个字符串s和t,写一个函数来确定t是否是s的回文词。
Example 1:

Input: s = "anagram", t = "nagaram"
Output: true

Example 2:

Input: s = "rat", t = "car"
Output: false

解决

1.数组 时间复杂度 O(N)

	//使用数组
    public boolean isAnagram(String s, String t) {
        if(s.length() != t.length())
            return false;
        int[] arrayS = new int[26];
        int[] arrayT = new int[26];
        char[] charsS = s.toCharArray();
        char[] charsT = t.toCharArray();
        for (char c : charsS) {
            arrayS[c - 'a'] ++;
        }
        for (char c : charsT) {
            arrayT[c - 'a'] ++;
        }
        for(int i = 0;i < 26;i++){
            if(arrayS[i] != arrayT[i])
                return false;
        }
        return true;
    }

2.hashmap 时间复杂度O(N) 但消耗的时间比数组会多很多

//使用hashmap
    public boolean isAnagram(String s, String t) {
        if(s.length() != t.length())
            return false;
        char[] charsS = s.toCharArray();
        char[] charsT = t.toCharArray();
        Map<Character,Integer> mapS = new HashMap<>();
        Map<Character,Integer> mapT = new HashMap<>();
        for(int i = 0;i < s.length();i ++){
            if(mapS.containsKey(charsS[i])){
                mapS.put(charsS[i],mapS.get(charsS[i])+1);
            }else {
                mapS.put(charsS[i],1);
            }
        }
        for(int i = 0;i < t.length();i ++){
            if(mapT.containsKey(charsT[i])){
                mapT.put(charsT[i],mapT.get(charsT[i])+1);
            }else {
                mapT.put(charsT[i],1);
            }
        }
        return mapS.equals(mapT);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值