-
-
Notifications
You must be signed in to change notification settings - Fork 361
[daehyun99] WEEK 05 Solutions #2764
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
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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,13 @@ | ||
| class Solution: | ||
| def maxProfit(self, prices: List[int]) -> int: | ||
| l = 0 | ||
| r = 0 | ||
| profit = 0 | ||
|
|
||
| while r < len(prices): | ||
| if prices[l] < prices[r]: | ||
| profit = max(prices[r]-prices[l], profit) | ||
| elif prices[l] > prices[r]: | ||
| l = r | ||
| r += 1 | ||
| return profit |
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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,31 @@ | ||
| class Solution: | ||
|
|
||
| def encode(self, strs: List[str]) -> str: | ||
| encoded_strs = "" | ||
| for s in strs: | ||
| encoded_strs += str(len(s)) | ||
| encoded_strs += "#" | ||
| for char in s: | ||
| encoded_strs += char | ||
| return encoded_strs | ||
|
|
||
| def decode(self, s: str) -> List[str]: | ||
| print(s) | ||
| decoded_strs = [] | ||
|
|
||
| idx = 0 | ||
| while idx < len(s): | ||
| end = idx + 1 | ||
| while s[end] != "#": | ||
| end += 1 | ||
| length = s[idx:end] | ||
| idx = end | ||
| decoded_str = "" | ||
| for i in range(int(length)): | ||
| idx += 1 | ||
| decoded_str += s[idx] | ||
| idx += 1 | ||
| decoded_strs.append(decoded_str) | ||
| return decoded_strs | ||
|
|
||
|
|
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🏷️ 알고리즘 패턴 분석
📊 시간/공간 복잡도 분석
피드백: 각 문자열에 대해 길이 26의 카운트 배열을 만들고 이를 튜플로 키로 사용한다. 해시맵으로 그룹을 관리한다. 개선 제안: 현재 구현이 적절해 보입니다.
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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,38 @@ | ||
| from collections import defaultdict | ||
| class Solution: | ||
| def groupAnagrams(self, strs: List[str]) -> List[List[str]]: | ||
| groups = defaultdict(list) | ||
|
|
||
| for s in strs: | ||
| count = [0] * 26 | ||
|
|
||
| for c in s: | ||
| count[ord(c)-ord('a')] += 1 | ||
|
|
||
| groups[tuple(count)].append(s) | ||
| return list(groups.values()) | ||
|
|
||
| """ | ||
| class Solution: | ||
| def groupAnagrams(self, strs: List[str]) -> List[List[str]]: | ||
| def decode(s, key, base): | ||
| for c in s: | ||
| key[ord(c) - base] += 1 | ||
| result = "" | ||
| for k in key: | ||
| result += ' ' + str(k) | ||
| return result | ||
| keys = {} | ||
| base_key = [0 for i in range(26)] | ||
| base = ord("a") | ||
|
|
||
| for s in strs: | ||
| key = decode(s, base_key.copy(), base) | ||
| temp = keys.get(key, []) | ||
| temp.append(s) | ||
| keys[key] = temp | ||
| results = [] | ||
| for val in keys.values(): | ||
| results.append(val) | ||
| return results | ||
| """ |
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🏷️ 알고리즘 패턴 분석
📊 시간/공간 복잡도 분석
피드백: 트라이 구조를 dict로 구현했고, 삽입 시 노드를 만들어가며 끝에 마커를 0 키로 표시한다. 탐색과 접두사 확인은 루프에 의해 각 문자에 대해 상수 시간을 수행한다. 개선 제안: 구현의 기본 흐름은 적절하지만, 삽입 시 최적화를 위해 리스트/딕셔너리 선택 여부를 재검토해볼 수 있습니다.
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 저는 별도의 TrieNode 라는 별도 클래스를 생성해서 풀었는데, 이렇게도 풀리네요 !
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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,43 @@ | ||
| class Trie: | ||
| def __init__(self): | ||
| self.root = dict() | ||
|
|
||
| def insert(self, word: str) -> None: | ||
| pointer = self.root | ||
| for char in word: | ||
| if char in pointer: | ||
| pointer = pointer[char] | ||
| continue | ||
| else: | ||
| pointer[char] = dict() | ||
| pointer = pointer[char] | ||
| pointer[0] = dict() | ||
|
|
||
| def search(self, word: str) -> bool: | ||
| pointer = self.root | ||
| for char in word: | ||
| if char in pointer: | ||
| pointer = pointer[char] | ||
| continue | ||
| else: | ||
| return False | ||
| if 0 in pointer: | ||
| return True | ||
| return False | ||
|
|
||
| def startsWith(self, prefix: str) -> bool: | ||
| pointer = self.root | ||
| for char in prefix: | ||
| if char in pointer: | ||
| pointer = pointer[char] | ||
| continue | ||
| else: | ||
| return False | ||
| 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) |
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🏷️ 알고리즘 패턴 분석
📊 시간/공간 복잡도 분석
피드백: 현재 구현은 모든 위치에서 사전에 있는 단어로 분리 가능한지 확인하고, 발견 시 위치를 큐에 추가한다. 최악의 경우 비효율 가능성이 존재한다. 개선 제안: 현재 구현이 적절해 보입니다.
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. BFS 로도 접근 가능하네요 ! |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| class Solution: | ||
| def wordBreak(self, s: str, wordDict: List[str]) -> bool: | ||
| pos = set() | ||
| pos.add(0) | ||
| len_s = len(s) | ||
|
|
||
| while len(pos) > 0 : | ||
| l = pos.pop() | ||
| for word in wordDict: | ||
| if s[l:].startswith(word): | ||
| pos.add(l+len(word)) | ||
| if l == len_s: | ||
| return True | ||
| return False |
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.
꽤 깔끔하게 잘 해결하셨네요!
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.
그리고
best time to buy and sell stock, 즉 해당 문제는
뒤에 로마 숫자를 붙혀서 1, 2, 3, 4, 5 총 다섯종류가 있는데요
dp 연습하기에 정말 괜찮은 문제라고 생각해서
2번문제
II는 한번 풀어보시길 추천드려요!