数据结构与算法(Python版) | (5) 堆栈OJ作业

Fiorenza ·
更新时间:2024-11-11
· 705 次阅读

OJ地址

1. 有效的括号

在这里插入图片描述

class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self,item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[len(self.items)-1] def size(self): return len(self.items) def parChecker(symbolString): s = Stack() index = 0 balanced = True if symbolString=="": return True while index<len(symbolString) and balanced: symbol = symbolString[index] if(symbol in '({['): s.push(symbol) else: if s.isEmpty(): balanced = False else: top = s.pop() if not matches(top,symbol): balanced = False index = index + 1 if s.isEmpty() and balanced: return True else: return False def matches(open,close): if '({['.index(open) == ')}]'.index(close): return True else: return False str = input() print(parChecker(str)) 2. 一维开心消消乐

在这里插入图片描述

class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self,item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[len(self.items)-1] def size(self): return len(self.items) def XXL(str): st = Stack() for s in str: if st.isEmpty(): st.push(s) else: if st.peek()==s: st.pop() else: st.push(s) alist = [] while not st.isEmpty(): alist.append(st.pop()) return ''.join(alist[::-1]) str = input() print(XXL(str)) 3. 强迫症老板和他的洗碗工

在这里插入图片描述

class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self,item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[len(self.items)-1] def size(self): return len(self.items) def remove(str): i = 0 j = 0 st = Stack() while i<=10 and j<=9: if not st.isEmpty() and int(str[j])==st.peek(): #栈里面存的是整数 需要把字符串中的整数用int()转换为整数 再比较 st.pop() j = j+1 else: st.push(i) i += 1 if st.isEmpty(): print('Yes') else: print('No') str = input() remove(str)
作者:CoreJT



数据 算法 数据结构 oj Python

需要 登录 后方可回复, 如果你还没有账号请 注册新账号