- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDecode_String.py
More file actions
Latest commit
70 lines (61 loc) · 2.25 KB
/
Copy pathDecode_String.py
File metadata and controls
70 lines (61 loc) · 2.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
classSolution:
defdecodeString(self, s: str) ->str:
defdfs(idx):
"""
DFS를 사용하는 방법
"""
result=""
number=""
i=idx
whilei<len(s):
iford("0") <=ord(s[i]) <=ord("9"):
number+=s[i]
elifs[i] =="[":
num=int(number)
number=""
output, idx=dfs(i+1)
i=idx
result+=num*output
elifs[i] =="]":
returnresult, i
else:
number=""
result+=s[i]
i+=1
returnresult, i
output, _=dfs(0)
returnoutput
defstacky(self, s):
"""
스택을 사용하는 방법
3[a2[c]] 의 경우 예시:
current_string = "c" 일 때의 stack은 [("", 3), ("a", 2)]
그리고, stack.pop()은 ("a", 2) 를 불러오고, "a" + 2 * "c" 를 수행
즉, "acc"가 완성. 다시, stack.pop()은 ("", 3)을 불러오고, "" + 3 * "acc"를 수행
"accaccacc"가 완성
"""
stack= []
current_string=""
k=0
forcharins:
ifchar=="[":
# 숫자로 구성된 문자열을 양수 k 로 치환하는데 성공하면, 이를 스택에 넣는다.
stack.append((current_string, k))
# 현재 문자열을 reset 시킴
current_string=""
k=0
elifchar=="]":
# We have completed this frame, get the last current_string and k from when the frame
# opened, which is the k we need to duplicate the current current_string by
last_string, last_k=stack.pop(-1)
current_string=last_string+last_k*current_string
elifchar.isdigit():
k=k*10+int(char)
else:
current_string+=char
returncurrent_string
a=Solution()
# jkjk
# print(a.decodeString("2[2[y]pq4[2[jk]e1[f]]]"))
# print(a.decodeString("3[a2[c]]"))
print(a.stacky("2[2[y]pq4[2[jk]e1[f]]]"))