LeetCode Top Interview Questions 242. Valid Anagram (Java版; Easy)

welcome to my blog

LeetCode Top Interview Questions 242. Valid Anagram (Java版; Easy)

题目描述
Given two strings s and t , write a function to determine if t is an anagram of s.

Example 1:

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

Input: s = "rat", t = "car"
Output: false
Note:
You may assume the string contains only lowercase alphabets.

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

解答:
使用哈希表而不是固定大小的计数器。想象一下,分配一个大的数组来适应整个 Unicode 字符范围,这个范围可能超过 100万。哈希表是一种更通用的解决方案,可以适应任何字符范围
第一次做; 使用bit map的思想, 因为小写字母一共26个, 所以用一个长度为26的整形数组就能统计各个字符出现的次数了
/*
借助哈希表可以实现时间复杂度O(N),空间复杂度O(N)的解法
其实借助数组就行, 因为字符串中全是小写字母, 所以只有26个, 用一个长度26的整型数组就能统计个数了! 这样空间复杂度就是O(1)了
*/
class Solution {
    public boolean isAnagram(String s, String t) {
        if((s==null && t!=null) || (s!=null && t==null))
            return false;
        if(s==null && t==null)
            return true;
        if(s.length()!=t.length())
            return false;
        //here, s.length()==t.length()
        int n = s.length();
        int[] lettermap = new int[26];
        //遍历字符串,统计每个字符出现的次数, s的字符使用正向统计, t的字符使用负向统计
        for(int i=0; i<n; i++){    
            lettermap[s.charAt(i)-'a']++;
            lettermap[t.charAt(i)-'a']--;
        }
        //遍历数组, 检查各个元素是否都是0
        for(int i=0; i<26; i++){
            if(lettermap[i]!=0)
                return false;
        }
        return true;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值