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)