编程小白的第一篇博文

编程小白的第一篇博文

问题:

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==’’

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值