题目描述:给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。注意:若 s 和 t 中每个字符出现的次数都相同,则称 s 和 t 互为字母异位词。
思考:考虑使用hashmap进行解答,对字符串s进行put +1操作,对字符串进行 put -1操作,当value值小于0的时候返回false。
创建hashmap
Map<Character, Integer> table = new HashMap<Character, Integer>();
对字符串s进行put操作。
char ch = t.charAt(i);
table.put(ch, table.getOrDefault(ch, 0) - 1);
对字符串t进行put -1操作并判断value值是否小于1。
char ch = t.charAt(i);
table.put(ch, table.getOrDefault(ch, 0) - 1);
if (table.get(ch) < 0) {
return false;
}