From 77e9a35240f030de284bc84b9890584436ac4a75 Mon Sep 17 00:00:00 2001 From: ChaedongIm Date: Sun, 12 Jan 2025 08:58:35 +0900 Subject: [PATCH 1/7] feat: [Week 06-1] solve valid-parentheses --- valid-parentheses/Chaedie.py | 67 ++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 valid-parentheses/Chaedie.py diff --git a/valid-parentheses/Chaedie.py b/valid-parentheses/Chaedie.py new file mode 100644 index 000000000..5ce30da46 --- /dev/null +++ b/valid-parentheses/Chaedie.py @@ -0,0 +1,67 @@ +""" +Solution: + 1) s 를 순회하면서 여는 괄호면 stack 에 push 한다. + 2) 닫는 괄호일 경우 각 case 별로 stack 의 최상단이 알맞는 여는 괄호이면 stack 을 pop 하고 아니면 False 를 return 한다. +Time: O(n) +Space: O(n) +""" + + +class Solution: + def isValid(self, s: str) -> bool: + stack = [] + left = ["(", "{", "["] + for char in s: + if char in left: + stack.append(char) + continue + + if not stack: + return False + + if char == ")": + if stack[-1] == "(": + stack.pop() + else: + return False + if char == "}": + if stack[-1] == "{": + stack.pop() + else: + return False + if char == "]": + if stack[-1] == "[": + stack.pop() + else: + return False + + return not stack + + +""" +Solution: + 1) stack과 hash map을 사용한다. + 2) s를 순회하면서 여는 괄호일 경우 stack 에 push + 3) 닫는 괄호일 경우 stack 이 비지 않으면서 최상단 요소가 알맞은 여는 괄호이면 stack pop, 아닐 경우 return False + +Time: O(n) +Space: O(n) +""" + + +class Solution: + def isValid(self, s: str) -> bool: + opening = "({[" + closing = ")}]" + closeToOpen = dict(zip(closing, opening)) + + stack = [] + for char in s: + if char in opening: + stack.append(char) + else: + if stack and stack[-1] == closeToOpen[char]: + stack.pop() + else: + return False + return not stack From 41046a98ad892518413e69bd9fbd3730b770a0a6 Mon Sep 17 00:00:00 2001 From: ChaedongIm Date: Sun, 12 Jan 2025 09:09:48 +0900 Subject: [PATCH 2/7] feat: [Week 06-2] solve container-with-most-water --- container-with-most-water/Chaedie.py | 43 ++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 container-with-most-water/Chaedie.py diff --git a/container-with-most-water/Chaedie.py b/container-with-most-water/Chaedie.py new file mode 100644 index 000000000..6bfb8a0c7 --- /dev/null +++ b/container-with-most-water/Chaedie.py @@ -0,0 +1,43 @@ +""" +Solution: Brute Force +Time: O(n^2) +Space: O(1) +""" + + +class Solution: + def maxArea(self, height: List[int]) -> int: + max_water = 0 + for i in range(len(height) - 1): + for j in range(i + 1, len(height)): + h = min(height[i], height[j]) + w = j - i + max_water = max(h * w, max_water) + + return max_water + + +""" +Solution: Two Pointer + 1) 포인터 이동은 left height, right height 중 작은 value를 가질 경우 이동 +Time: O(n) +Space: O(1) +""" + + +class Solution: + def maxArea(self, height: List[int]) -> int: + l = 0 + r = len(height) - 1 + max_water = 0 + + while l < r: + h = min(height[l], height[r]) + w = r - l + max_water = max(h * w, max_water) + + if height[l] < height[r]: + l += 1 + else: + r -= 1 + return max_water From d60f81151950043a61bf973accabe7a677179e7a Mon Sep 17 00:00:00 2001 From: ChaedongIm Date: Sun, 12 Jan 2025 10:20:56 +0900 Subject: [PATCH 3/7] feat: [Week 06-3] solve design-add-and-search-words-data-structure --- .../Chaedie.py | 112 ++++++++++++++++++ 1 file changed, 112 insertions(+) create mode 100644 design-add-and-search-words-data-structure/Chaedie.py diff --git a/design-add-and-search-words-data-structure/Chaedie.py b/design-add-and-search-words-data-structure/Chaedie.py new file mode 100644 index 000000000..dba53ecbe --- /dev/null +++ b/design-add-and-search-words-data-structure/Chaedie.py @@ -0,0 +1,112 @@ +""" +풀이를 보고 공부했습니다. + +Solution: + set을 이용, + 1) addWord 에선 add + 2) search 에선 .을 포함한 모든 글자가 동일한 단어가 있는지 확인 + +search + Time: O(n * w) + Space: O(1) +""" + + +class WordDictionary: + + def __init__(self): + self.root = set() + + def addWord(self, word: str) -> None: + self.root.add(word) + + def search(self, word: str) -> bool: + for candidate in self.root: + if len(candidate) != len(word): + continue + if all(w == c or w == "." for w, c in zip(word, candidate)): + return True + return False + + +""" +풀이를 보고 공부했습니다. + +Solution: Trie - 달레의 코드 +""" + + +class WordDictionary: + + def __init__(self): + self.root = {"$": True} + + def addWord(self, word: str) -> None: + node = self.root + for ch in word: + if ch not in node: + node[ch] = {"$": False} + node = node[ch] + node["$"] = True + + def search(self, word: str) -> bool: + def dfs(node, idx): + if idx == len(word): + return node["$"] + + ch = word[idx] + if ch in node: + return dfs(node[ch], idx + 1) + if ch == ".": + if any(dfs(node[k], idx + 1) for k in node if k != "$"): + return True + return False + + return dfs(self.root, 0) + + +""" +풀이를 보고 공부했습니다. + +Solution: Trie with TrieNode - NeetCode +""" + + +class TrieNode: + def __init__(self): + self.children = {} # a: TrieNode + self.word = False + + +class WordDictionary: + + def __init__(self): + self.root = TrieNode() + + def addWord(self, word: str) -> None: + cur = self.root + + for c in word: + if c not in cur.children: + cur.children[c] = TrieNode() + cur = cur.children[c] + cur.word = True + + def search(self, word: str) -> bool: + def dfs(j, root): + cur = root + for i in range(j, len(word)): + c = word[i] + + if c == ".": + for child in cur.children.values(): + if dfs(i + 1, child): + return True + return False + else: + if c not in cur.children: + return False + cur = cur.children[c] + return cur.word + + return dfs(0, self.root) From 721c972a785beb31efe1990fa8359584c296e6d2 Mon Sep 17 00:00:00 2001 From: ChaedongIm Date: Tue, 14 Jan 2025 15:07:35 +0900 Subject: [PATCH 4/7] feat: [Week 06-5] solve spiral-matrix --- spiral-matrix/Chaedie.py | 46 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 spiral-matrix/Chaedie.py diff --git a/spiral-matrix/Chaedie.py b/spiral-matrix/Chaedie.py new file mode 100644 index 000000000..62a7c977e --- /dev/null +++ b/spiral-matrix/Chaedie.py @@ -0,0 +1,46 @@ +""" +Solution: + 1) 좌우 상하의 경계를 좁혀가며 순회한다. + 2) 탈출 조건으로 result 의 사이즈가 matrix 의 원소 갯수가 같아지는지 확인한다. + (탈출 조건을 좌우 상하 경계가 넘어가는 시험을 기준으로 삼은 솔루션을 봤지만, 정확히 이해는 되지 않아 사이즈 비교로 진행했습니다.) +Time: O(m * n) +Space: O(1) +""" + + +class Solution: + def spiralOrder(self, matrix: List[List[int]]) -> List[int]: + result = [] + left, right = 0, len(matrix[0]) + top, bottom = 0, len(matrix) + + while left < right and top < bottom: + for i in range(left, right): + result.append(matrix[top][i]) + top += 1 + + if len(result) == len(matrix[0]) * len(matrix): + break + + for i in range(top, bottom): + result.append(matrix[i][right - 1]) + right -= 1 + + if len(result) == len(matrix[0]) * len(matrix): + break + + for i in range(right - 1, left - 1, -1): + result.append(matrix[bottom - 1][i]) + bottom -= 1 + + if len(result) == len(matrix[0]) * len(matrix): + break + + for i in range(bottom - 1, top - 1, -1): + result.append(matrix[i][left]) + left += 1 + + if len(result) == len(matrix[0]) * len(matrix): + break + + return result From 9b3dbce7751e6e733882d102ed691a4831730b7c Mon Sep 17 00:00:00 2001 From: ChaedongIm Date: Tue, 14 Jan 2025 16:52:30 +0900 Subject: [PATCH 5/7] feat: [Week 05-3] solve encode-and-decode-strings --- encode-and-decode-strings/Chaedie.py | 44 ++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 encode-and-decode-strings/Chaedie.py diff --git a/encode-and-decode-strings/Chaedie.py b/encode-and-decode-strings/Chaedie.py new file mode 100644 index 000000000..6f3c97e0c --- /dev/null +++ b/encode-and-decode-strings/Chaedie.py @@ -0,0 +1,44 @@ +""" +Solution: + 1) encode: 각 글자의 앞에 글자수와 # 라는 delimiter 를 붙여 stringify 한다. + 2) decode: length 를 참고삼아 word를 따내어 result 배열을 만든다. + +Time: O(n) +Space: O(n) +""" + + +class Codec: + + def encode(self, strs: List[str]) -> str: + """Encodes a list of strings to a single string.""" + result = "" + for word in strs: + result += str(len(word)) + result += "#" + result += word + return result + + def decode(self, s: str) -> List[str]: + """Decodes a single string to a list of strings.""" + i = 0 + result = [] + length = "" + while i < len(s): + # find number + length = "" + while s[i] is not "#": + length += s[i] + i += 1 + # find # + i += 1 + # find word + result.append(s[i : i + int(length)]) + i += int(length) + + return result + + +# Your Codec object will be instantiated and called as such: +# codec = Codec() +# codec.decode(codec.encode(strs)) From 8b31585a6fd19a8e4fcf1c802bf69070b5580a31 Mon Sep 17 00:00:00 2001 From: ChaedongIm Date: Tue, 14 Jan 2025 17:45:31 +0900 Subject: [PATCH 6/7] feat: [Week 06-4] solve longest-increasing-subsequence --- longest-increasing-subsequence/Chaedie.py | 44 +++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 longest-increasing-subsequence/Chaedie.py diff --git a/longest-increasing-subsequence/Chaedie.py b/longest-increasing-subsequence/Chaedie.py new file mode 100644 index 000000000..d26b76f1f --- /dev/null +++ b/longest-increasing-subsequence/Chaedie.py @@ -0,0 +1,44 @@ +""" +Solution: 1) DFS Brute Force -> TLE +Time: O(2^n * nlogn) +""" + + +class Solution: + def lengthOfLIS(self, nums: List[int]) -> int: + + sub = [] + max_len = 0 + + def dfs(i, length): + nonlocal max_len + if i == len(nums): + if sub == sorted(list(set(sub))): + max_len = max(len(sub), max_len) + return + + dfs(i + 1, length) + sub.append(nums[i]) + dfs(i + 1, length) + sub.pop() + + dfs(0, 0) + return max_len + + +""" +풀이를 보고 적었으며, 완벽히 이해 되지는 않습니다. +Time: O(n^2) +Space: O(n) +""" + + +class Solution: + def lengthOfLIS(self, nums: List[int]) -> int: + LIS = [1] * len(nums) + + for i in range(len(nums) - 1, -1, -1): + for j in range(i + 1, len(nums)): + if nums[i] < nums[j]: + LIS[i] = max(LIS[i], 1 + LIS[j]) + return max(LIS) From 6eccf0fc0fe613f681961c111d3122e803320081 Mon Sep 17 00:00:00 2001 From: ChaedongIm Date: Sat, 18 Jan 2025 09:07:50 +0900 Subject: [PATCH 7/7] =?UTF-8?q?docs:=20=EB=A6=AC=EB=B7=B0=20=EB=B0=98?= =?UTF-8?q?=EC=98=81=20-=20method=20=EA=B0=80=20=EC=97=AC=EB=9F=AC?= =?UTF-8?q?=EA=B0=9C=EC=9D=BC=20=EA=B2=BD=EC=9A=B0=20=EC=8B=9C=EA=B3=B5?= =?UTF-8?q?=EA=B0=84=20=EB=B3=B5=EC=9E=A1=EB=8F=84=20=EA=B3=84=EC=82=B0=20?= =?UTF-8?q?=EA=B0=81=EA=B0=81=20=EC=A7=84=ED=96=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- encode-and-decode-strings/Chaedie.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/encode-and-decode-strings/Chaedie.py b/encode-and-decode-strings/Chaedie.py index 6f3c97e0c..7494060a9 100644 --- a/encode-and-decode-strings/Chaedie.py +++ b/encode-and-decode-strings/Chaedie.py @@ -3,8 +3,13 @@ 1) encode: 각 글자의 앞에 글자수와 # 라는 delimiter 를 붙여 stringify 한다. 2) decode: length 를 참고삼아 word를 따내어 result 배열을 만든다. -Time: O(n) -Space: O(n) +encode: + Time: O(n) (n: strs 배열의 길이만큼 연산) + Space: O(1) + +decode: + Time: O(n) (n: s 의 길이만큼 연산) + Space: O(m) (m: decode 이후 배열의 길이) """