LeetCode242 - 有效的字母异位词(难度:简单)
链接:https://leetcode-cn.com/problems/valid-anagram
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。
示例 1:
输入: s = "anagram", t = "nagaram"
输出: true
示例 2:
输入: s = "rat", t = "car"
输出: false
说明:
你可以假设字符串只包含小写字母。
进阶:
如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况?
解法一:
算法复杂度分析:排序时间复杂度nlogn,字符串比较n,整体O(nlogn+n) -> O(nlogn)
空间复杂度分析:额外空间存储char[] 空间复杂度=O(n)
class Solution {
public boolean isAnagram(String s, String t) {
if(s == null || t == null || t.length() != s.length() ) return false;
char[] stemp = s.toCharArray();
char[] ttemp = t.toCharArray();
Arrays.sort(stemp);
Arrays.sort(ttemp);
return new String(stemp).equals(new String(ttemp));
}
}
解法二:
算法复杂度分析:遍历时间复杂度O(n)
空间复杂度分析:额外空间存储O(S),即字符集大小,如果字符集中样本越多,存储的空间越大,但是适用于Unicode
class Solution {
public boolean isAnagram(String s, String t) {
if(s == null || t == null || s.length() != t.length()) return false;
Map<Character, Integer> map = new HashMap<>();
// 遍历s
for(int i=0; i<s.length(); i++) {
map.put(s.charAt(i), map.getOrDefault(s.charAt(i), 0) + 1);
}
// 遍历t
for(int i=0; i<t.length(); i++) {
map.put(t.charAt(i), map.getOrDefault(t.charAt(i), 0) - 1);
if(map.getOrDefault(t.charAt(i), 0) < 0) {
return false;
}
}
return true;
}
}