Hash Map 5

[LeetCode] 1166. Design File System

createPath 함수에 주어지는 input 중 하나인 path를 '/'로 split해 parent path와 비교해가며 함수를 완성하려 했지만, Test case에 번번히 걸려 다른 방법으로 풀었다. split을 통해 '/'로 path를 자르는건 동일하지만 split 된 list에서 마지막 요소만 제외하고 하나의 String으로 다시 구성해 parent에 대한 True/False를 확인하는 방식으로 풀었다. get 함수는 Hash map을 통해 수월하게 구현했다. class FileSystem: def __init__(self): self.p = {} def createPath(self, path: str, value: int) -> bool: if path in self.p: return False..

[LeetCode] 1165. Single-Row Keyboard

알파벳 26개로 구성된 keyboard String이 input으로 주어지고 0부터 25까지를 개개의 index로 간주하고, Hash map의 key로 keyboard의 각 character를 value로 넣은 후, 또 다른 input인 word의 character를 앞에서 하나씩 읽어들여 각각을 Hash map의 key로서 value를 찾는다. 그리고 차이(절대값)의 누적합을 반환했다. class Solution: def calculateTime(self, keyboard: str, word: str) -> int: dic = {} p = 0 ret = 0 for i, k in enumerate(keyboard): dic[k] = i for i, w in enumerate(word): ret += ab..

[LeetCode] 359. Logger Rate Limiter

같은 message가 10초 안에 다시 Print 되지 않도록 확인하는 함수를 만들면 된다. 파이썬의 해시맵을 사용해 해당 message의 timestamp를 확인하고 갱신해 True/False를 반환한다. class Logger: def __init__(self): self.d = defaultdict(int) def shouldPrintMessage(self, timestamp: int, message: str) -> bool: if message not in self.d: self.d[message] = timestamp return True else: if timestamp - self.d[message] < 10: return False else: self.d[message] = timestam..

[LeetCode] 290. Word Pattern

Easy 문제로 설명과 예시는 아래와 같다. : Given a pattern and a string s, find if s follows the same pattern. Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s. Pattern과 String이 주어지고 주어진 String은 공백(space)를 통해 단어를 구분해뒀고, 각 단어를 하나의 문자로 치환했을 때 주어진 pattern과 일치가 가능하다면 true 그렇지 않으면 false를 반환하면 된다. Easy 문제임에도 acceptance rate는 41.7% 밖에 되지 않는다. Dictiona..

[Tech, etc.] Hash 검색 시간 복잡도(Search Time complexity)

Hash에서 특정 key에 대한 value를 확인할 때 걸리는 시간 복잡도가 O(1) - Constant time 이라는 것에 대한 이해가 되지 않아 확인해보니 실제로는 O(1)보다는 오래 걸리지만 거의 그 즈음 걸리기에 O(1)으로 표기한다는 것을 알았다. 내가 잘못 이해하고 있었던 부분은 Search와 Index(Access)의 차이다. Search는 한 자료 구조(Data Structure) 안에서 특정 요소(element)를 검색하는 것을 의미하는 반면, Index(Access)는 이미 어디 있는지 알고 이를 접근한다는 차이를 가지고 이해를 해야했다. List의 경우에도 Index를 알고 있다면 바로 접근이 가능 하기에 O(1)의 시간 복잡도를 갖지만, 특정 데이터(data)를 검색한다는 것은 L..