Skip to content

Commit d82761b

Browse files
authored
Merge pull request #898 from Jay-Mo-99/main
[Jay-Mo-99] Week 6
2 parents 8be8ae2 + 727931f commit d82761b

File tree

3 files changed

+218
-0
lines changed

3 files changed

+218
-0
lines changed
+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
 #해석
2+
#s는 start index, e는 ending index로 할당한다.
3+
#area 에 (e-s)*min(height[e], height[s]) 로 면적의 넓이를 구한다.
4+
#만약 height[s]가 height[e] 보다 작다면, 현 area보다 더 큰 결괏값을 위해 변화를 준다.
5+
# (e-s)에서 e를 줄어들면 필연적으로 area 값이 기존보다 적어진다. 따라서 s에 1을 더해 인덱스를 오른쪽으로 이동시켜 height[s] 에 변화를 준다.
6+
#그 외의 상황에는 height[e]를 변화시키기 위해 e에 1를 빼 왼쪽 인덱스로 이동시킨다.
7+
#해당 루프는 s가 e보다 작을때 작용된다. 만약 s의 증가와 e의 감소로 두 변수가 마주치면 종료한 후 max_area를 return시킨다.
8+
9+
10+
11+
#Big O
12+
#- N: height의 element 갯수
13+
14+
#Time Complexity: O(N)
15+
#- while : s와 e가 만날때까지 최대 N번 반복된다. 각 반복에서의 연산들은 O(1)에 해당된다. -> O(N)
16+
17+
18+
#Space Complexity: O(1)
19+
#- s,e,max_area: 변수는 상수로 작용된다 -> O(1)
20+
####
21+
#
22+
#
23+
class Solution(object):
24+
def maxArea(self, height):
25+
"""
26+
:type height: List[int]
27+
:rtype: int
28+
"""
29+
max_area = 0 #Saving for answer
30+
s,e=0,len(height)-1 #Assign the first index and last index
31+
while s<e:
32+
area = (e-s) * min(height[s],height[e]) #Current area using e,s
33+
max_area = max(area, max_area) #Re-assing the max_area comparing with area
34+
if height[s]< height[e]:
35+
s+=1
36+
else:
37+
e -=1
38+
return max_area
39+
40+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
# 해석
2+
# 0. TrieNode 클래스 정의:
3+
# - 각 TrieNode 인스턴스는 다음의 두 가지 속성을 가진다:
4+
# 1) children: 현재 노드의 자식 노드들을 저장하는 딕셔너리 (문자 -> TrieNode 인스턴스).
5+
# 2) is_end_of_word: 현재 노드가 단어의 끝인지 나타내는 Boolean 값.
6+
7+
# 1. WordDictionary 클래스 정의:
8+
# - WordDictionary 클래스는 Trie 자료구조를 사용하여 단어를 저장(addWord)하고 탐색(search)한다.
9+
10+
# 1-1. __init__ 함수:
11+
# - root는 TrieNode 클래스로 생성된 인스턴스를 가진다.
12+
# - Trie 자료구조의 시작점(루트 노드) 역할을 한다.
13+
14+
# 1-2. addWord 함수:
15+
# 1) 루트 노드(self.root)에서 시작.
16+
# 2) 단어의 각 문자를 순회하며:
17+
# - 현재 노드의 children에 문자가 없으면, 새 TrieNode를 생성해 추가.
18+
# - 현재 노드를 해당 문자의 자식 노드로 이동.
19+
# 3) 단어의 마지막 문자를 처리한 후, 해당 노드의 is_end_of_word를 True로 설정.
20+
21+
22+
# 1-3. search 함수:
23+
# - 주어진 단어가 Trie에 존재하는지 확인하는 함수.
24+
# - 와일드카드 문자(.)를 처리할 수 있다.
25+
# - 내부적으로 dfs(깊이 우선 탐색) 함수를 사용하여 트라이를 탐색.
26+
# - dfs(index, node):
27+
# 1) 종료 조건: index가 단어 길이에 도달하면, 현재 노드의 is_end_of_word 반환.
28+
# 2) 현재 문자가 '.'인 경우:
29+
# - 현재 노드의 모든 자식 노드에 대해 dfs를 호출.
30+
# - 하나라도 True를 반환하면 True 반환.
31+
# 3) 현재 문자가 일반 문자인 경우:
32+
# - 자식 노드에 문자가 없으면 False 반환.
33+
# - 자식 노드로 이동해 dfs를 재귀 호출.
34+
35+
36+
37+
#Big O
38+
# - N: 저장된 모든 단어의 총 문자 수 (Trie에 저장된 모든 문자의 개수).
39+
# - C: 알파벳의 개수 (영어 기준 최대 26).
40+
41+
#Time Complexity: O(N)
42+
#- addWord함수 : N에 기반하여 단어 추가
43+
#- searchWord 함수:
44+
# - 일반 탐색: O(n), n은 단어의 길이.
45+
# - 와일드카드 탐색: 최악의 경우 O(C^N),
46+
# - C는 알파벳 개수 (최대 26).
47+
# - N은 단어의 길이. 와일드카드 문자가 많을수록 모든 경로를 탐색해야 할 수도 있음.
48+
49+
# - Space Complexity: O(N × C)
50+
#
51+
# - 각 노드는:
52+
# 1) children 딕셔너리를 통해 자식 노드를 저장 (메모리 사용).
53+
# 2) is_end_of_word 변수 (Boolean 값, O(1)).
54+
# - Trie에 저장된 단어의 문자 수가 많을수록 메모리 사용량 증가.
55+
56+
class TrieNode:
57+
def __init__(self):
58+
self.children = {} #알파벳 a부터 z까지를 자식으로 가짐, 크기 26의 배열이나 딕셔너리를 사용.
59+
self.is_end_of_word = False #어떤 단어의 끝인지 나타내는 Boolean 값
60+
#예를 들어, "note"이라는 단어의 'e'에 해당하는 노드의 is_end_of_word가 True, 'n'
61+
62+
class WordDictionary:
63+
def __init__(self):
64+
self.root = TrieNode() # WD로 생성된 인스턴스.root = TrieNode 인스턴스
65+
66+
def addWord(self, word: str) -> None:
67+
node = self.root #node에 self.root를 부여
68+
for char in word: # 매개변수 word를 하나씩 순회하며 char에 저장 (예: word="note" -> char="n", "o", "t", "e")
69+
if char not in node.children: # 만약 char가 현재 노드의 자식 노드 목록에 없다면
70+
node.children[char] = TrieNode()
71+
#node.children[char]을 TrideNode 인스턴스로 생성
72+
# self.root.children = {
73+
# "n": TrieNode() # "n" 키가 추가되고, 값으로 새로운 TrieNode 인스턴스가 들어감
74+
# }
75+
76+
#Example1:
77+
#root
78+
#└── "n" (children={}, is_end_of_word=False)
79+
80+
#Example2:
81+
#└── "n" (children={}, is_end_of_word=False)
82+
# └── "o" (children={}, is_end_of_word=False)
83+
node = node.children[char] #node를 현 node의 children[char]로 이동
84+
#Example1:
85+
# node = node.children["n"]
86+
87+
#Example2:
88+
# node = node.children["o"]
89+
node.is_end_of_word = True
90+
#After for loop, 끝 노드의 is_end_of_word를 True로 전환
91+
92+
#Example 4:
93+
#root
94+
#└── "n"
95+
#└── "o"
96+
#└── "t"
97+
#└── "e" (children={}, is_end_of_word=True)
98+
99+
def search(self, word: str) -> bool:
100+
def dfs(index, node): # DFS 함수 정의
101+
# 1) 종료 조건: 모든 문자를 탐색한 경우
102+
if index == len(word):
103+
return node.is_end_of_word # 단어 끝 여부 반환
104+
# 2) 현재 문자 처리
105+
char = word[index]
106+
if char == '.': # 2-1) 와일드카드인 경우
107+
for child in node.children.values(): # 모든 자식 노드 탐색
108+
if dfs(index + 1, child): #dfs를 재귀호출 하여 다음 노드로 탐색 재개
109+
return True #재귀 이후에 있으면 True
110+
return False #없으면 False
111+
else: # 2-2) 일반 문자 처리
112+
if char not in node.children: # 현재 문자가 자식 노드에 없는 경우 False
113+
return False
114+
return dfs(index + 1, node.children[char]) # 다음 노드로 이동하여 탐색
115+
116+
return dfs(0, self.root)
117+
#1. def dfs를 self.root 위치에서 첫 호출.
118+
119+
120+
121+

valid-parentheses/Jay-Mo-99.py

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
 #해석
2+
#매개변수 string s의 각 character인 c 가 open bracket이면 temp 리스트에 추가한다.
3+
#c가 close bracket이면 temp의 마지막 element와 짝이 맞는지 검사한다. 짝이 아니거나 temp에 아무 요소도 없으면 return false
4+
#검사 이후 temp에 잔여 요소가 남아있으면 짝이 맞지 않았다는 뜻이니 return false, 아닐 경우 return true
5+
#
6+
7+
#Big O
8+
#- N: 문자열 s의 길이
9+
10+
#Time Complexity: O(N) = O(N) + O(1)
11+
#- for c in s : string s의 character의 수 만큼 진행된다. -> O(N)
12+
#-temp.append(c), temp.pop() : 리스트 연산은 상수 취급 -> O(1)
13+
14+
#Space Complexity: O(N)
15+
#- temp : list temp은 최대 string s의 character수 만큼 요소를 저장할 가능성이 있다.
16+
17+
18+
class Solution(object):
19+
def isValid(self, s):
20+
"""
21+
:type s: str
22+
:rtype: bool
23+
"""
24+
temp = []
25+
for c in s:
26+
#If c is Open bracket, append to the list
27+
if (c == "(") or (c=="{") or (c=="["):
28+
temp.append(c)
29+
#If C is Close bracket, Check the close bracket pairs with last elememt of temp list
30+
else:
31+
#There's no element in the tmep, Return false
32+
if(len(temp)==0):
33+
return False
34+
35+
if(c==")") and (temp.pop()=="("):
36+
continue
37+
if(c=="}") and (temp.pop()=="{"):
38+
continue
39+
if(c=="]") and (temp.pop()=="["):
40+
continue
41+
else:
42+
return False
43+
44+
#After loop, Check temp is empty or not.
45+
#If all c of s is pairs each other, the temp list is empty.
46+
if (len(temp) == 0) :
47+
return True
48+
else:
49+
return False
50+
51+
52+
53+
54+
55+
56+
57+

0 commit comments

Comments
 (0)