Checking whether python- with a stack balanced parentheses string / strings reverse

Stack (Stack) is in the computer field collection of a widely used, the stack is a linear collection, access is strictly limited to a period called the top (top). For example, wanted to stack a pile of clean dishes every time you take a new plate, are on the top of the stack of plates of the most, when you fill the plate when added, is also on the top, at the in the bottom of the dish, you might never use. The most common operation of the stack, there are the following two:
Push (a) # pressed into the press-fitting of a stack
pop () # pop, the last element of the stack pop

Whether stack checking brackets string balance

Algorithm thinking:
1. sequential scan arithmetic expression (expressed as a string), left parenthesis when faced with three types of time for the brackets into the stack;
2. When scanning to a certain type of right parenthesis, comparing the current whether the top element match, if match is determined to continue de-stacked;
3. if the current top of the stack does not match the current scan brackets, the brackets on the order of incorrect pairing, the match fails, exit;
4. if the string right parenthesis currently being some type stack is empty, than the right parenthesis left parenthesis, the match fails, exit;
5. string scanning cycle ends, when the stack not empty (i.e., there are certain types of stacks left brackets), then the left parenthesis than right parenthesis, the match fails;
6 correctly matches the normal end of the bracket.

class Stack(object):
    def __init__(self, limit=10):
        self.stack = [] #存放元素
        self.limit = limit #栈容量极限
    def push(self, data): #判断栈是否溢出
        if len(self.stack) >= self.limit:
            print('StackOverflowError')
            pass
        self.stack.append(data) #没有溢出将data放入self.stack
    def pop(self):
        if self.stack: 
            return self.stack.pop()
        else:
            raise IndexError('pop from an empty stack') #空栈不能被弹出
    def peek(self): #查看堆栈的最上面的元素
        if self.stack:
            return self.stack[-1]
    def is_empty(self): #判断栈是否为空
        return not bool(self.stack)
    def size(self): #返回栈的大小
        return len(self.stack)
def balanced_parentheses(parentheses):
    stack = Stack(len(parentheses))
    for parenthesis in parentheses: #字符串的每个元素
        if parenthesis == '(':    #如果是左括号,压栈
            stack.push(parenthesis)
        elif parenthesis == ')': 如果是右括号,判断栈是不是空,为空则不匹配,返回False
            if stack.is_empty():
                return False
            stack.pop() #不为空,则左右匹配,将之前压栈的左括号弹出,进行下一个字符的匹配
    return stack.is_empty() 返回布尔类型
if __name__ == '__main__':
    examples = ['((()))', '((())', '(()))']
    print('Balanced parentheses demonstration:\n')
    for example in examples:
        print(example + ': ' + str(balanced_parentheses(example)))

The results:
Balanced parentheses Demonstration:

((())): True
((()): False
(())): False

Simply put, the left bracket is met, then the stack, right parenthesis met:
1) to determine whether there are elements within the stack, it does not appear after the first right-left, unbalanced, returns False
2) and then determine whether the top element the current right parenthesis match, if not match, returns False, if matched, delete the top element, continue to the next cycle
Finally, after the end of the cycle, to determine whether there are elements within the stack, it indicates that there is more than the number of left parenthesis right parenthesis, unbalanced ,Mismatch. No explanation about the balance and returns True.

To reverse a string:

def str_reverse(str):
    s = Stack()
    result = ''
    for i in str:
        s.push(i)
    while not s.is_empty():
        result += s.pop()
    return result 

Guess you like

Origin blog.csdn.net/xavier_muse/article/details/90647541