checkio (Brackets)

本文探讨如何通过算法判断给定表达式中括号的正确匹配性,涉及不同类型的括号组合,如花括号、圆括号和方括号。通过实例演示算法应用,确保表达式的逻辑性和准确性。

You are given an expression with numbers, brackets and operators. For this task only the brackets matter. Brackets come in three flavors: "{}" "()" or "[]". Brackets are used to determine scope or to restrict some expression. If a bracket is open, then it must be closed with a closing bracket of the same type. The scope of a bracket must not intersected by another bracket. For this task, you should to make a decision to correct an expression or not based on the brackets. Do not worry about operators and operands.

Input: An expression with different of types brackets. A string (unicode).

Output: The correctness the expression or don’t. A boolean.

Example:

?
1
2
3
4
5
6
checkio("((5+3)*2+1)")==True
checkio("{[(3+1)+2]+}")==True
checkio("(3+{1-1)}")==False
checkio("[1+1]+(2*2)-{3/3}")==True
checkio("(({[(((1)-2)+3)-3]/3}-3)")==False
checkio("2+3")==True

How it is used: When you write code or complex expressions in a mathematical package, you can get huge headache when it comes to excess or missing brackets. This concept can be useful for your own IDE.

Precondition: There are only brackets ("{}" "()" or "[]"), digits or operators ("+" "-" "*" "/").
0 < |expression| < 103


判断括号是否匹配,不好好思考还挺容易写错的,换了3个思路才过。

record = {}

def check(expression, target1, target2):
    tag1 = tag2 = None
    reverse_expression = expression[::-1]
    tag1 = expression.find(target1)
    tag2 = reverse_expression.find(target2)
    if tag1 == -1 and tag2 == -1:
        return True
    if tag2 == -1 or tag1 == -1:
        return False
    tag2 = len(expression)-tag2-1
    return checkio(expression[tag1+1:tag2])

def checkio(expression):
    if expression in record:
        return record[expression]
    record[expression] = check(expression, '(', ')') and check(expression, '[', ']') and check(expression, '{', '}')
    return record[expression]


print checkio('(((([[[{{{3}}}]]]]))))')
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
    assert checkio(u"((5+3)*2+1)") == True, "Simple"
    assert checkio(u"{[(3+1)+2]+}") == True, "Different types"
    assert checkio(u"(3+{1-1)}") == False, ") is alone inside {}"
    assert checkio(u"[1+1]+(2*2)-{3/3}") == True, "Different operators"
    assert checkio(u"(({[(((1)-2)+3)-3]/3}-3)") == False, "One is redundant"
    assert checkio(u"2+3") == True, "No brackets, no problem"

一个非常美的代码,虽然效率不高

def checkio(Expression):
    'Check expression for correct brackets order'
    x = "".join(a for a in Expression if a in "{}()[]")
    while ("()" in x) or ("[]" in x) or ("{}" in x):
        x=x.replace("()","")
        x=x.replace("{}","")
        x=x.replace("[]","")
    return len(x)==0

C - Brackets Stack Query / Time Limit: 3 sec / Memory Limit: 1024 MiB Score : 300 points Problem Statement A string T is called a good bracket sequence if and only if it satisfies the following condition: T can be made into an empty string by repeating the following operation zero or more times: Choose () contained in T as a (contiguous) substring and remove it. For example, (), (()()), and the empty string are good bracket sequences, but )()( and ))) are not good bracket sequences. There is a string S. Initially, S is an empty string. Process Q queries in the order they are given. After each query, determine whether S is a good bracket sequence. There are two types of queries: 1 c: A character c is given. c is either ( or ). Append c to the end of S. 2: Remove the last character of S. It is guaranteed that S is not an empty string at this time. Constraints 1≤Q≤8×10 5 c in queries of the first type is ( or ). It is guaranteed that S is not empty when a query of the second type is given. Q is an integer. Input The input is given from Standard Input in the following format, where query i ​ denotes the i-th query. Q query 1 ​ query 2 ​ ⋮ query Q ​ Each query is given in one of the following two formats: 1 c 2 Output Output Q lines. The i-th line should contain Yes if the string S immediately after processing the i-th query is a good bracket sequence, and No otherwise. Sample Input 1 Copy 8 1 ( 2 1 ( 1 ) 2 1 ( 1 ) 1 ) Sample Output 1 Copy No Yes No Yes No No No Yes S immediately after processing the 1st query is (, which is not a good bracket sequence. S immediately after processing the 2nd query is an empty string, which is a good bracket sequence. S immediately after processing the 3rd query is (, which is not a good bracket sequence. S immediately after processing the 4th query is (), which is a good bracket sequence. S immediately after processing the 5th query is (, which is not a good bracket sequence. S immediately after processing the 6th query is ((, which is not a good bracket sequence. S immediately after processing the 7th query is ((), which is not a good bracket sequence. S immediately after processing the 8th query is (()), which is a good bracket sequence.c++
最新发布
10-20
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值