zoukankan      html  css  js  c++  java
  • python栈之多符号类型的匹配

     1 from pythonds import Stack
     2 def parChecker(symbolString):
     3     s = Stack()
     4     balanced = True   #声明一个布尔变量
     5     index = 0
     6     while index < len(symbolString) and balanced:  #len函数定下标
     7         symbol = symbolString[index]
     8         if symbol in "([{":     #开括号压入栈,注意字符串与子串的特性
     9             s.push(symbol)
    10         else:
    11             if s.isEmpty():
    12                 balanced = False
    13             else:
    14                 top = s.pop()   
    15                 if not matches(top,symbol):   #将栈中待删除的顶部元素与字符串中下一个待与之匹配的右闭符号比较
    16                     balanced = False
    17         index = index + 1
    18     if balanced and s.isEmpty():      #python中if convention即if convention  is True!!注意此行的位置,与while并列
    19         return True
    20     else:
    21         return False
    22 def matches(open,close):
    23     opens = "([{"                     #开括号,待压入栈
    24     closers = ")]}"                   #闭括号  待与栈匹配后一起删除
    25     return opens.index(open) == closers.index(close)   #输出的是布尔值,str1.index(str2)输出子串str2在str1中的起始位置
  • 相关阅读:
    HDU 4123 Bob’s Race 树的直径+ST表
    acm 2015北京网络赛 F Couple Trees 树链剖分+主席树
    acm java入门(转载)
    java水题集
    南昌网络赛C.Angry FFF Party
    eclipse 安装
    eclipse jdk安装
    树链剖分总结
    P
    L
  • 原文地址:https://www.cnblogs.com/Henry-ZHAO/p/12725359.html
Copyright © 2011-2022 走看看