[HackerRank][Python3] Tries: Contacts
2018. 8. 5. 15:58 |
프로그래밍/HackerRank
Problem :
https://www.hackerrank.com/challenges/ctci-contacts/problem
My Solution :
#!/usr/bin/env python3 class Node(object): def __init__(self): self.children = {} self.count = 0 class Trie(object): def __init__(self): self.head = Node() def add(self, data): curr = self.head for c in data: curr = curr.children.setdefault(c, Node()) curr.count += 1 def find(self, data): curr = self.head for c in data: if c not in curr.children: return 0 curr = curr.children[c] return curr.count n = int(input()) trie = Trie() for _ in range(n): op, contact = input().split() if op == 'add': trie.add(contact) else: print(trie.find(contact))
My Solution2 :
아래는 위처럼 직접 class를 설계하지 않고, 기본 dictionary 자료구조를 활용한 버전이다.
#!/usr/bin/env python3 def add_contact(trie, contact): curr = trie for c in contact: curr = curr.setdefault(c, {}) curr['count'] = curr.setdefault('count', 0) + 1 def find_contact(trie, contact): curr = trie for c in contact: if c not in curr: return 0 curr = curr[c] return curr['count'] n = int(input()) trie = {} for _ in range(n): op, contact = input().split() if op == 'add': add_contact(trie, contact) else: print(find_contact(trie, contact))
My Solution3 :
이번에는 dictionary 대신 크기 27짜리 list를 활용해 보았다. 입력은 소문자이기 때문에 26개 칸은 소문자 - 97을 Index로 사용하고, 마지막 칸에는 count를 저장하였다.
#!/usr/bin/env python3 def add_contact(trie, contact): curr = trie for c in contact: pos = ord(c)-97 if not curr[pos]: curr[pos] = [0]*27 curr = curr[pos] curr[26] += 1 def find_contact(trie, contact): curr = trie for c in contact: pos = ord(c)-97 if not curr[pos]: return 0 curr = curr[pos] return curr[26] n = int(input()) trie = [0]*27 for _ in range(n): op, contact = input().split() if op == 'add': add_contact(trie, contact) else: print(find_contact(trie, contact))
'프로그래밍 > HackerRank' 카테고리의 다른 글
[HackerRank][Python3] Equal Stacks (0) | 2018.09.02 |
---|---|
[HackerRank][Python3] Maximum Element (0) | 2018.09.02 |
[HackerRank][Python3] Matrix Layer Rotation (2) | 2018.08.08 |
[HackerRank][Python3] Dijkstra: Shortest Reach 2 (0) | 2018.08.07 |
[HackerRank][Python3] Swap Nodes [Algo] (0) | 2018.07.27 |
[HackerRank][Python3] Special Palindrome Again (0) | 2018.07.23 |
[HackerRank][Python3] Fraudulent Activity Notifications (0) | 2018.07.23 |
[HackerRank][Python3] Merge Sort: Counting Inversions (0) | 2018.07.22 |
최근에 달린 댓글 최근에 달린 댓글