Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
Tags
- binary tree
- 중간
- 이진트리
- two pointers
- 리트코드
- list
- Binary
- 재귀
- 미디움
- DP
- hash table
- dfs
- HashTable
- math
- leetcode
- tree
- 쉬움
- matrix
- recursive
- easy
- Python
- Array
- 문자열
- binary search
- linked list
- backtracking
- string
- sorting
- Depth-first Search
- Medium
Archives
- Today
- Total
부부의 코딩 성장 일기
LeetCode 242(Valid Anagram, Python) 본문
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)
'Algorithm > LeetCode' 카테고리의 다른 글
LeetCode 257(Binary Tree Paths, Python) (0) | 2024.02.18 |
---|---|
LeetCode 97(Interleaving String, Python) (0) | 2024.02.17 |
LeetCode 234(Palindrome Linked List, Python) (0) | 2024.02.15 |
LeetCode 232(Implement Queue using Stacks) (0) | 2024.02.14 |
LeetCode 225(Implement Stack using Queues) (0) | 2024.02.13 |