Given two strings s and t, return true if t is an anagram of s, and false otherwise.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
s_counter = Counter(s)
t_counter = Counter(t)
return s_counter == t_counter # return boolean type
from collections import Counter
class Solution(object):
def isAnagram(self, s, t):
return Counter(s) == Counter(t)
class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) {
return false;
}
int[] arr = new int[26];
for(int i = 0; i < s.length(); i++) {
arr[s.charAt(i) - 'a']++;
arr[t.charAt(i) - 'a']--;
}
for(int i = 0; i < 26; i++) {
if (arr[i] < 0) {
return false;
}
}
return true;
}
}
파이썬은 Counter를 사용하여 간단하게 카운트하였고, Java는 a ~ z까지의 개수를 담는 배열을 생성하여 s, t의 문자 개수를 저장하도록 했다. 만약 배열의 값이 0 미만이라면 아나그램이 아니므로 false를 리턴하였다.
다른사람의 풀이 중, s와 t 문자열을 sort하고 값이 일치하는 방법이 있었다.
def sol(s, t):
return sorted(s) == sorted(t) # 43ms