diff --git a/design-add-and-search-words-data-structure/sadie100.ts b/design-add-and-search-words-data-structure/sadie100.ts new file mode 100644 index 0000000000..106390b0d5 --- /dev/null +++ b/design-add-and-search-words-data-structure/sadie100.ts @@ -0,0 +1,72 @@ +/* +words를 맵형태로 저장, 각 스펠링과 다음에 나오는 문자열을 key-value로 하는 맵으로 저장 +.의 경우 모든 경우를 탐색한다 + +시간복잡도 : + addWord : O(L) (L은 words의 길이) + search : 일반적으로 O(L), .이 많으면 O(26^k) (k는 .의 개수) + +*/ +class TrieNode { + children: Map + isEnd: boolean + + constructor() { + this.children = new Map() + this.isEnd = false + } +} + +class WordDictionary { + words = new TrieNode() + constructor() {} + + addWord(word: string): void { + let curWords = this.words + + for (let i = 0; i < word.length; i++) { + const char = word[i] + + if (!curWords.children.has(char)) { + curWords.children.set(char, new TrieNode()) + } + + curWords = curWords.children.get(char) + } + curWords.isEnd = true + } + + search(word: string): boolean { + return this.searchRecursively(word, this.words) + } + + searchRecursively(word: string, area: TrieNode) { + for (let i = 0; i < word.length; i++) { + if (!area) return false + const char = word[i] + + if (char === '.') { + const values = [...area.children.values()] + + for (let newArea of values) { + const result = this.searchRecursively(word.slice(i + 1), newArea) + if (result) return true + } + return false + } else { + if (!area.children.has(char)) return false + area = area.children.get(char) + } + } + + if (area.isEnd) return true + return false + } +} + +/** + * Your WordDictionary object will be instantiated and called as such: + * var obj = new WordDictionary() + * obj.addWord(word) + * var param_2 = obj.search(word) + */ diff --git a/reverse-linked-list/sadie100.ts b/reverse-linked-list/sadie100.ts new file mode 100644 index 0000000000..4334a7dd16 --- /dev/null +++ b/reverse-linked-list/sadie100.ts @@ -0,0 +1,34 @@ +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +/* +직전 노드를 담는 변수 before과 다음 노드를 담는 변수 next, 순회중인 노드 head 변수와 함께 list를 순회 +head의 next에 before을 넣고, head를 next로 변환하며 head가 null이 아닐 때까지 반복한다 + +시간복잡도 : O(N) - 1번 순회 +공간복잡도 : O(1) - before, next 변수 + +*/ +function reverseList(head: ListNode | null): ListNode | null { + if (!head) return head + let originNext = head.next + let before = null + + while (head !== null) { + originNext = head.next + head.next = before + before = head + head = originNext + } + + return before +}