-
-
Notifications
You must be signed in to change notification settings - Fork 247
[devyejin] WEEK 05 solutions #1838
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
Open
devyejin
wants to merge
5
commits into
DaleStudy:main
Choose a base branch
from
devyejin:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
7e37d94
best time to buy and sell stock solution
devyejin 0138b06
word break solution
devyejin b4d98cc
encode and decode strings solution
devyejin 4273f10
implement trie prefix tree solution
devyejin 6f7ed62
group anagrams solution
devyejin File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
# time complexity : O(n) | ||
# space complexity : O(1) | ||
from typing import List | ||
|
||
|
||
class Solution: | ||
def maxProfit(self, prices: List[int]) -> int: | ||
n = len(prices) | ||
min_price = prices[0] | ||
max_profit = 0 | ||
|
||
for i in range(1, n): | ||
min_price = min(min_price, prices[i]) | ||
max_profit = max(max_profit, prices[i] - min_price) | ||
|
||
return max_profit |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
class Solution: | ||
""" | ||
@param: strs: a list of strings | ||
@return: encodes a list of strings to a single string. | ||
""" | ||
|
||
def encode(self, strs): | ||
# write your code here | ||
result = "" | ||
for s in strs: | ||
result += str(len(s)) + "@" + s | ||
return result | ||
|
||
""" | ||
@param: str: A string | ||
@return: decodes a single string to a list of strings | ||
""" | ||
|
||
def decode(self, str): | ||
# write your code here | ||
result = [] | ||
i = 0 | ||
while i < len(str): | ||
j = i | ||
# 시작점 아닌 경우 | ||
while str[j] != "@": | ||
j += 1 | ||
# 시작점인 경우 | ||
length = int(str[i:j]) | ||
word = str[j + 1: j + 1 + length] | ||
result.append(word) | ||
i = j + 1 + length | ||
return result |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
from typing import List | ||
from collections import Counter, defaultdict | ||
|
||
# class Solution: | ||
# def groupAnagrams(self, strs: List[str]) -> List[List[str]]: | ||
# | ||
# dict_anagrams = defaultdict(list) | ||
# for idx, word in enumerate(strs): | ||
# key = tuple(sorted(Counter(word).items())) | ||
# dict_anagrams[key].append(word) | ||
# | ||
# return list(dict_anagrams.values()) | ||
class Solution: | ||
def groupAnagrams(self, strs: List[str]) -> List[List[str]]: | ||
|
||
dict_anagrams = defaultdict(list) | ||
for word in strs: | ||
key = "".join(sorted(word)) | ||
dict_anagrams[key].append(word) | ||
|
||
return list(dict_anagrams.values()) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
class TrieNode: | ||
def __init__(self): | ||
self.isEnd = False | ||
self.links = {} | ||
|
||
|
||
class Trie: | ||
|
||
def __init__(self): | ||
self._root = TrieNode() | ||
|
||
def _recurAdd(self, node: TrieNode, word: str) -> None: | ||
if not word: | ||
node.isEnd = True | ||
return | ||
|
||
ch = word[0] | ||
# 부모 노드의 자식에 있는지 확인 | ||
next_link = node.links.get(ch) | ||
|
||
if not next_link: | ||
node.links[ch] = TrieNode() | ||
next_link = node.links[ch] | ||
|
||
self._recurAdd(next_link, word[1:]) | ||
|
||
def insert(self, word: str) -> None: | ||
if not word: | ||
return | ||
|
||
self._recurAdd(self._root, word) | ||
|
||
def _recurSearch(self, node: TrieNode, word: str) -> bool: | ||
if not word: | ||
return node.isEnd | ||
|
||
ch = word[0] | ||
next_link = node.links.get(ch) | ||
if next_link: | ||
return self._recurSearch(next_link, word[1:]) | ||
return False | ||
|
||
def search(self, word: str) -> bool: | ||
if not word: | ||
return False | ||
|
||
return self._recurSearch(self._root, word) | ||
|
||
def startsWith(self, prefix: str) -> bool: | ||
node = self._root | ||
for ch in prefix: | ||
if ch not in node.links: | ||
return False | ||
node = node.links[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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
from typing import List | ||
|
||
|
||
class Solution: | ||
def wordBreak(self, s: str, wordDict: List[str]) -> bool: | ||
def dfs(subs: str): | ||
if subs in memo: | ||
return memo[subs] | ||
|
||
if not subs: | ||
return True | ||
|
||
for word in wordDict: | ||
if subs.startswith(word): | ||
if dfs(subs[len(word):]): | ||
memo[subs] = True | ||
return True | ||
|
||
memo[subs] = False | ||
return False | ||
|
||
memo = {} | ||
return dfs(s) | ||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
prices가 빈 배열일 경우 prices[0] 접근에서 IndexError 발생 가능 → 입력 검증 필요
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
문제 조건에서 prices 길이가 1이상이라는 문구가 있어서 저런식으로 처리하긴했는데, 그래도 안전하게 검증 로직 넣는게 좋을까요?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
아 제가 조건을 못 봤네요. 이 문제에서는 해당 사항 고려하지 않으셔도 됩니다.