Repository navigation
Expand file tree
/
Copy pathStack.py
More file actions
118 lines (95 loc) · 3.03 KB
/
Copy pathStack.py
File metadata and controls
118 lines (95 loc) · 3.03 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# =============================================
# 스택(Stack) 예제
# =============================================
# ==================== 기본 스택 구현 ====================
print("=== 기본 스택 구현 ===")
stack = []
# push - 데이터 삽입
stack.append(10)
stack.append(20)
stack.append(30)
print(f"push 후: {stack}") # [10, 20, 30]
# pop - 데이터 제거 및 반환
top = stack.pop()
print(f"pop된 값: {top}") # 30
print(f"pop 후: {stack}") # [10, 20]
# 스택 최상단 확인 (제거하지 않음)
if stack:
print(f"top 값: {stack[-1]}") # 20
# 비어있는지 확인
print(f"스택 비었는지: {len(stack) == 0}") # False
# ==================== 스택 클래스 구현 ====================
print("\n=== 스택 클래스 구현 ===")
class Stack:
def __init__(self, max_size=10):
self.stack = []
self.max_size = max_size
def is_full(self):
return len(self.stack) == self.max_size
def is_empty(self):
return len(self.stack) == 0
def push(self, data):
if self.is_full():
print("스택이 가득 찼습니다.")
else:
self.stack.append(data)
def pop(self):
if self.is_empty():
print("스택이 비어있습니다.")
return None
return self.stack.pop()
def peek(self):
if self.is_empty():
return None
return self.stack[-1]
s = Stack()
s.push(1)
s.push(2)
s.push(3)
print(f"peek: {s.peek()}") # 3
print(f"pop: {s.pop()}") # 3
print(f"peek: {s.peek()}") # 2
# ==================== 괄호 검사 ====================
print("\n=== 괄호 검사 ===")
def check_parentheses(st):
"""소괄호가 올바르게 짝지어졌는지 확인"""
stack = []
for c in st:
if c == "(":
stack.append(c)
elif c == ")":
if not stack:
return False
stack.pop()
return len(stack) == 0
# 테스트
print(check_parentheses("(())")) # True
print(check_parentheses("(()")) # False
print(check_parentheses("())")) # False
print(check_parentheses("((()))")) # True
# ==================== 짝지어 제거하기 ====================
print("\n=== 짝지어 제거하기 ===")
def remove_pairs(st):
"""연속된 같은 문자 짝을 제거"""
stack = []
for c in st:
if stack and stack[-1] == c:
stack.pop()
else:
stack.append(c)
return 1 if not stack else 0
# 테스트
print(remove_pairs("baabaa")) # 1 (모두 제거됨)
print(remove_pairs("cdcd")) # 0 (제거 불가)
print(remove_pairs("aabbcc")) # 1
# ==================== 역순 문자열 ====================
print("\n=== 역순 문자열 ===")
def reverse_string(s):
"""스택을 이용한 문자열 뒤집기"""
stack = list(s)
result = ""
while stack:
result += stack.pop()
return result
print(reverse_string("hello")) # olleh
print(reverse_string("Python")) # nohtyP