给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。
示例 1: 输入: s = "anagram", t = "nagaram" 输出: true
示例 2: 输入: s = "rat", t = "car" 输出: false
说明: 你可以假设字符串只包含小写字母。
正解
1)Set存出现过的char,HashMap用来统计出现的个数
class Solution {
public static boolean isAnagram(String s, String t) {
HashSet<Character> set = new HashSet();
HashMap<Character,Integer> map1 = new HashMap();
HashMap<Character,Integer> map2 = new HashMap();
char temp1 = '0';
char temp2 = '0';
boolean flag = false;
if (s.length() == t.length()) {//先判断长度是否相同
for (int i = 0; i < s.length(); i++) {
temp1 = s.charAt(i);
temp2 = t.charAt(i);
if (!map1.containsKey(temp1)) {//储存出现过的char,和两个String的个数
set.add(temp1);
map1.put(temp1, 1);
} else {
map1.put(temp1, (int) (map1.get(temp1)) + 1);
}
if (!map2.containsKey(temp2)) {
map2.put(temp2, 1);
} else {
map2.put(temp2, (int) (map2.get(temp2)) + 1);
}
}
for (char str : set) {
if (map2.get(str)!=null && map1.get(str).equals(map2.get(str))){
flag=true;
}else {
return false;
}
}
}
return flag;
}
}
(注意点:在这里必须用“map1.get(str).equals(map2.get(str))”来判断两者值是否相同,若用==,比较的是其内存中的地址(也可以说是HashCode),由于两个哈希表不同,他们储存数值的地址是相互独立的)
2)本题中只有字符串,我们可以用一个数组来代替哈希表的作用
class Solution {
public boolean isAnagram(String s, String t) {
int[] record = new int[26];
for (char c : s.toCharArray()) {
record[c - 'a'] += 1;
}
for (char c : t.toCharArray()) {
record[c - 'a'] -= 1;
}
for (int i : record) {
if (i != 0) {
return false;
}
}
return true;
}
}