有效字母异位词
本题由于元素数较少,则可采用数组方式记录每个元素的值(自己为了方便,则直接map,耗时增加,但也能解出)
将较短的字符串,去记录其每个字符出现频率;较长的字符串,后续去比较;防止后一个字符串过短,还没比较完前者的频次结果,程序就结束了;因而若发现后一字符串较短,则直接交换二者的对象。
前一个字符串频次结果记录完毕,再遍历后一个字符串去比,若发现相同的字符,则对应的频次减一,若发现频次有-1,则说明同样字符有多,则不匹配;若发现后一字符串某个字符没有,则说明前者无该字符,则不匹配;总体上就这两种不匹配的结果。
//给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。
//
// 注意:若 s 和 t 中每个字符出现的次数都相同,则称 s 和 t 互为字母异位词。
//
//
//
// 示例 1:
//
//
//输入: s = "anagram", t = "nagaram"
//输出: true
//
//
// 示例 2:
//
//
//输入: s = "rat", t = "car"
//输出: false
//
//
//
// 提示:
//
//
// 1 <= s.length, t.length <= 5 * 10⁴
// s 和 t 仅包含小写字母
//
//
//
//
// 进阶: 如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况?
//
// Related Topics 哈希表 字符串 排序 👍 862 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
Map<Character , Integer> sResult = new HashMap();
public boolean isAnagram(String s, String t) {
if(s.length() > t.length()){
String temp = s;
s = t;
t = temp;
}
for(int i = 0;i < s.length();i++){
Character search = s.charAt(i);
Integer count = sResult.get(search);
if(count != null){
sResult.put(search, ++count);
} else {
sResult.put(search, 1);
}
}
for(int i = 0;i < t.length();i++){
Character search = t.charAt(i);
Integer count = sResult.get(search);
//发现不存在的字符,则判定不符合
if(count == null){
return false;
}
count--;
//发现字符计数被减到0以下,则判定不符合
if(count < 0){
return false;
}
sResult.put(search, count);
}
return true;
}
}
//leetcode submit region end(Prohibit modification and deletion)
rue;
}
}
//leetcode submit region end(Prohibit modification and deletion)