给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的 字母异位词。
示例 1:
输入: s = "anagram", t = "nagaram" 输出: true
示例 2:
输入: s = "rat", t = "car" 输出: false
提示:
1 <= s.length, t.length <= 5 * 104s和t仅包含小写字母
这道题我看了别人的好像是直接定义一个26大小的数组存放对应数据个数,我的方法和其类似,不过今天正好学到了Map,就用HashMap解决了。
class Solution {
public boolean isAnagram(String s, String t) {
HashMap<Character, Integer> hm = new HashMap<>();
int length1 = s.length();
int length2 = t.length();
if(length1 != length2) return false;//长度不一样直接返回
Set<Character> keySet = hm.keySet();//创建键的集合
for (int i = 0; i < length1; i++) {//遍历s
char temp = s.charAt(i);
if(keySet.contains(temp)){//若包含该键则取出数据进行加1操作后重新添加覆盖原数据
int count = hm.get(temp);
count++;
hm.put(temp, count);
}else{//不包含则第一次添加
hm.put(temp, 1);
}
}
for (int i = 0; i < length1; i++) {//与上述遍历过程类似遍历t
char temp = t.charAt(i);
if(keySet.contains(temp)){
int count = hm.get(temp);
count--;//区别在于此次遍历是减操作
hm.put(temp, count);
}else{
return false;//如果是前一次遍历后不包含的则直接返回
}
}
for (Map.Entry<Character, Integer> entry : hm.entrySet()) {//采用增强for遍历判断
if(entry.getValue() != 0)
return false;
}
return true;
}
}

593

被折叠的 条评论
为什么被折叠?



