Given two strings
s
andt
, returntrue
ift
is an anagram ofs
, andfalse
otherwise.给定两个字符串s和t,如果t是s的字母异位词,则返回true,否则返回false。
Example 1:
Input: s = "anagram", t = "nagaram" Output: trueExample 2:
Input: s = "rat", t = "car" Output: falseConstraints:
1 <= s.length, t.length <= 5 * 104
s
andt
consist of lowercase English letters.Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
这一题可以用哈希法和排序,用哈希进行计数
class Solution {
//直接排序
public boolean isAnagram1(String s, String t) {
char[] sChars = s.toCharArray();
char[] tChars = t.toCharArray();
Arrays.sort(sChars);
Arrays.sort(tChars);
return Arrays.equals(sChars, tChars);
}
//哈希的方法
public boolean isAnagram2(String s, String t) {
Map<Character, Integer> map = new HashMap<>();
for (char ch : s.toCharArray()) {
map.put(ch, map.getOrDefault(ch, 0) + 1);
}
for (char ch : t.toCharArray()) {
Integer count = map.get(ch);
if (count == null) {
return false;
} else if (count > 1) {
map.put(ch, count - 1);
} else {
map.remove(ch);
}
}
return map.isEmpty();
}
//转换成数组比较
public boolean isAnagram3(String s, String t) {
int[] sCounts = new int[26];
int[] tCounts = new int[26];
for (char ch : s.toCharArray()) {
sCounts[ch - 'a']++;
}
for (char ch : t.toCharArray()) {
tCounts[ch - 'a']++;
}
for (int i = 0; i < 26; i++) {
if (sCounts[i] != tCounts[i]) {
return false;
}
}
return true;
}
public boolean isAnagram4(String s, String t) {
int[] counts = new int[26];
t.chars().forEach(tc -> counts[tc - 'a']++);
s.chars().forEach(cs -> counts[cs - 'a']--);
return Arrays.stream(counts).allMatch(c -> c == 0);
}
public boolean isAnagram(String s, String t) {
return Arrays.equals(s.chars().sorted().toArray(), t.chars().sorted().toArray());
}
}