Algorithm/LeetCode
LeetCode 242(Valid Anagram, Python)
펩시_콜라
2024. 2. 16. 19:00
1. 문제 링크
LeetCode - The World's Leading Online Programming Learning Platform
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
2. 문제 설명
- 문자열 s와 t가 주어졌을 때, 만약 t가 s의 Anagram이라면 True를 반환, 아니라면 False를 반환
- 여기서 Anagram이란, 일반적으로 모든 원래 문자를 정확히 한번 사용하여 다른 단어나 구문의 문자를 재배열해서 형성된 단어나 구문을 뜻함
- 예시1) 문자열 s="nagaram"은 단어의 배치를 재정렬했을 때 문자열 t="anagram"이 될 수 있으므로, True
- 예시2) 문자열 s="rat"은 단어 배치를 재정렬해도 t="car"가 될 수 없으므로 False를 반환
3. 처음 풀이
- 단어를 재정렬했을 때 다른 단어가 되는지 여부라면, 그냥 두 문자열을 정렬했을 때 같은질 판단하면 되므로,
- sorted(s) == sorted(t)를 반환하는 것으로 코드 작성
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return sorted(s) == sorted(t)
4. 다른 풀이
- submission된 다른 풀이들을 봤을 때, 난이도 easy문제라서 특별한 풀이가 있진 않았다.
- Counter 함수를 써서, 각 단어 별 count를 dict형태로 만들어, 해당 값이 동일한지 여부로 판단한 케이스도 많았다.
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return Counter(s) == Counter(t)