0
点赞
收藏
分享

微信扫一扫

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 条评论