Given two strings s and t, return true if t is an anagram of s, and false otherwise.
Input: s = "anagram", t = "nagaram"
Output: true
Input: s = "rat", t = "car"
Output: false
1 <= s.length, t.length <= 5 * 10^4
s
and t
consist of lowercase English letters.What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
문자열에서 문자들의 종류와 개수가 모두 같은지 파악한다.
class Solution {
public boolean isAnagram(String s, String t) {
int count = 0;
if (s.length() != t.length()){
return false;
}
String[] arr1 = s.split("");
HashMap<String, Integer> hm1 = new HashMap<>();
for (String ss : arr1) {
hm1.put(ss, hm1.getOrDefault(ss, 0) + 1);
}
String[] arr2 = t.split("");
HashMap<String, Integer> hm2 = new HashMap<>();
for (String ss : arr2) {
hm2.put(ss, hm2.getOrDefault(ss, 0) + 1);
}
for (Map.Entry<String, Integer> entry : hm1.entrySet()) {
if (hm2.containsKey(entry.getKey()) && hm2.get(entry.getKey()).equals(entry.getValue())) {
count++;
}
}
if (count == hm1.size()) {
return true;
}
return false;
}
}
class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()){
return false;
}
String[] arr1 = s.split("");
String[] arr2 = t.split("");
Arrays.sort(arr1);
Arrays.sort(arr2);
for (int i = 0; i < arr1.length; i++) {
if (!arr1[i].equals(arr2[i])) {
return false;
}
}
return true;
}
}