问题:
Write a function that takes a string of braces, and determines if the order of the braces is valid. It should return true if the string is valid, and false if it’s invalid.
This Kata is similar to the Valid Parentheses Kata, but introduces new characters: brackets [], and curly braces {}. Thanks to @arnedag for the idea!
All input strings will be nonempty, and will only consist of parentheses, brackets and curly braces: ()[]{}.
What is considered Valid?
A string of braces is considered valid if all braces are matched with the correct brace.
Examples:
“(){}[]” => True
“([{}])” => True
“(}” => False
“[(])” => False
“[({})](]” => False
解题方法
所有前括号要么与后一个字符组成一个括号,要么和对称位的字符组成一个括号。
第一种:创建字典,以前括号为键,后括号为键值;创建空列表。然后使用for循环来判断字符串的每一个字符是否为键,如果为键,则传入列表,如果不为键,则判断该字符是否是列表中最后一个字符在字典中对应的键值,如果不是则返回False。或者在这个非键字符传入是列表已经为空了,也返回False。核心思想就是第一个出现的后括号和它前面的字符一定是一对,然后把它前面的字符给剔除掉,继续往后判断。
第二种:使用while循环,把字符串中的括号都替换为空字符串。
代码
第一种:
def validBraces(string):
braces = {"(": “)”, “[”: “]”, “{”: “}”}
stack = []
for character in string:
if character in braces.keys():
stack.append(character)
else:
if len(stack) == 0 or braces[stack.pop()] != character:
return False
return len(stack) == 0
第二种:
def validBraces(s):
while ‘{}’ in s or ‘()’ in s or ‘[]’ in s:
s=s.replace(’{}’,’’)
s=s.replace(’[]’,’’)
s=s.replace(’()’,’’)
return s==’’