242. Valid Anagram
1. Description
- Given two strings
sandt, returntrueif the two strings are anagrams of each other, otherwise returnfalse. - An anagram is a string that contains the exact same characters as another string, but the order of the characters can be different.
2. Example
Example 1
Input: s = “racecar”, t = “carrace” Output: true
Example 2
Input: s = “jar”, t = “jam” Output: false
3. Solution
- 첫번째 풀이
- Runtime: 21ms
- 설명
sorted함수로 정렬- 문자열 길이 확인하여 두 문자열이 다르면 False
for문 다돌고 리턴이 없다면return True
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
new_s = sorted(s)
new_t = sorted(t)
if len(new_s) == len(new_t):
for i in range(len(new_s)):
if new_s[i] == new_t[i]:
pass
else:
return False
return True
else:
return False- 📌Runtime을 조금 더 줄일 수 있는 방법에 대해 궁금하여 런타임이 짧은 코드를 봤다.
- 코드가 어느정도 비슷했지만 두 개의 코드가 제일 대표적인거 같아 보았다.
- 두번째 풀이
- Runtime: 4ms
- 설명
-
collectionsmodule의 Counter클래스를 사용한다. -Counter클래스는 중복된 데이터가 문자열이나 리스트를 인자로 넘기면 각 원소가 몇 번씩 나오는지가 저장된 객체를 얻게 된다. -Counter클래스를 통해s와t문자열의 문자들이 같은 개수라면True, 다르면False
from collections import Counter
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return Counter(s) == Counter(t)- 📌Counter클래스는 알고리즘 문제를 풀 때 자주 사용되는 클래스중 하나이니 알아두는 것이 좋을 거 같다.
- 세번째 풀이
- Runtime: 3ms
- 설명
- 문자열의 길이가 같지 않다면
return False s문자열의 type을set로 바꾸어 중복되는 문자들을 지운 집합을for문을 돌린다.s와t에set(s)의 원소를 넣었을 때s와t에 원소의 개수가 다르면return Falsefor문이 다 끝나면return True
- 문자열의 길이가 같지 않다면
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
for i in set(s):
if s.count(i) != t.count(i):
return False
return True- 📌문자열
count함수는 특정 문자를 문자열에서 찾을 때 유용하다.set()를 통해 집합으로 만들어 중복을 삭제하고 남은 문자열들이s와t에 둘다 있으면 ANIGRAM이 되었다는 뜻이다.
4. What I Learned
References