leetcode-day13:Valid Anagram(有效的字母异位词)

242. Valid Anagram

哈希表:可以拿数组当哈希表来用,但哈希值不要太大

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

Example 1:

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

Example 2:

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

Constraints:

1 <= s.length, t.length <= 5 * 104
s and t consist of lowercase English letters.

Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?

逻辑分析:

暴力解法:
1.双层循环,外层s,内层t
2.不断寻找 t 中数组是否有 s 当前字母(注意判断重复情况),条件为否返回false,退出循环
3.返回 true

更优解法:
hash底层结构为数组+链表,或者数组+红黑树。所以数组就是简单的hash
1.新建长度为26的数据
2.遍历 s ,字母出现,将数组中对应下标的值加1(下标为字母的ascii码减去a的ascii码)
3.遍历 t ,字母出现,将数组中相应下标对应的值减1
4.遍历数组,遇到不为0的则返回false,否则返回true

JAVA代码实现:

class Solution {
    public boolean isAnagram(String s, String t) {
        int[] records = new int[26];
        //s放入数据对应值
        for(char c:s.toCharArray()){
            records[c-'a']+=1;
        }
        //t消减字符对应值
        for(char c:t.toCharArray()){
            records[c-'a']-=1;
        }
        //判断是否完全为0
        for(int i=0;i<records.length;i++){
            if(records[i]!=0){
                return false;
            }
        }
        return true;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值