Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[thispath98] Week 6 #895

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions best-time-to-buy-and-sell-stock/thispath98.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
class Solution:
def maxProfit(self, prices: List[int]) -> int:
minimum = prices[0]
answer = 0
for i in range(1, len(prices)):
if minimum > prices[i]:
minimum = prices[i]
else:
diff = prices[i] - minimum
if answer < diff:
answer = diff
return answer
6 changes: 6 additions & 0 deletions encode-and-decode-strings/thispath98.py
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

아하핳... 저도 처음에 이렇게 풀었었는데, 문제에 숨은 의도를 좀 더 파악해 보는것도 괜찮을것 같아요!

Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
class Codec:
def encode(self, strs: List[str]) -> str:
return "\n".join(strs)

def decode(self, s: str) -> List[str]:
return s.split("\n")
10 changes: 10 additions & 0 deletions group-anagrams/thispath98.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from collections import defaultdict

class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
anagram_dict = defaultdict(list)
for string in strs:
anagram_dict[tuple(sorted(string))].append(string)

answer = list(anagram_dict.values())
return answer
Comment on lines +3 to +10
Copy link
Contributor

@KwonNayeon KwonNayeon Jan 18, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

리뷰가 늦어져서 죄송합니다. 저는 if-else문을 활용해서 키가 존재하는지의 여부를 체크했는데, defaultdict(list)를 사용하면 예외처리를 더 간단하게 할 수 있다는 걸 알게 됐습니다! 이번 주도 고생하셨습니다!

42 changes: 42 additions & 0 deletions implement-trie-prefix-tree/thispath98.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
class Node:
def __init__(self, is_end=False):
self.child = {}
self.is_end = is_end


class Trie:
def __init__(self):
self.root = Node()

def insert(self, word: str) -> None:
node = self.root
for ch in word:
if ch not in node.child:
node.child[ch] = Node()
node = node.child[ch]
node.is_end = True

def search(self, word: str) -> bool:
node = self.root
for ch in word:
if ch not in node.child:
return False
node = node.child[ch]

return node.is_end

def startsWith(self, prefix: str) -> bool:
node = self.root
for ch in prefix:
if ch not in node.child:
return False
node = node.child[ch]

return True


# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)
34 changes: 34 additions & 0 deletions valid-parentheses/thispath98.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
class Solution:
def isValid(self, s: str) -> bool:
"""
Intuition:
stack 자료구조를 사용해서 닫히는 괄호가 올 경우
stack의 마지막과 일치하는지 확인한다.

Time Complexity:
O(N):
문자열을 한번 스캔하면서 조건문을 확인하므로
O(N)의 시간복잡도가 소요된다.

Space Complexity:
O(N):
최악의 경우 문자열 개수만큼 stack에 저장한다.
"""
stack = []
for ch in s:
if ch in ["(", "{", "["]:
stack.append(ch)
elif ch in [")", "}", "]"]:
if stack and (
(ch == ")" and stack[-1] == "(")
or (ch == "}" and stack[-1] == "{")
or (ch == "]" and stack[-1] == "[")
):
stack.pop()
else:
return False

if stack:
return False
else:
return True
Comment on lines +31 to +34
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

return 시 stack의 사이즈를 비교하는 걸로 하면 한줄로 줄일 수 있을것 같아요!

Comment on lines +17 to +34
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

코드가 직관적이라 이해하기 쉬웠습니다! 딕셔너리를 활용하여 코드를 조금 더 간결하게 개선할 수 있을 것 같습니다.

20 changes: 20 additions & 0 deletions word-break/thispath98.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
checked = set()

def dfs(idx):
if idx in checked:
return
checked.add(idx)

if idx == len(s):
return True

for word in wordDict:
word_len = len(word)
if s[idx: idx + word_len] == word:
if dfs(idx + word_len):
return True
return False

return dfs(0)
Loading