python 最小括号翻转次数?

w8biq8rn  于 2023-01-29  发布在  Python
关注(0)|答案(3)|浏览(135)

给定一个仅包含"}"和"{"的表达式。该表达式可能不平衡。请找出使表达式平衡的最小反向括号数
......Python'' a =['}{}{}}}{{{{}{}}{{}}{{}}{{']

for elem in a:
    sol=0
    stack=[]
 #stack.append(elem[i])
    i=0
    while i<len(elem)-1:
        if elem[i]=='{' and elem[i+1]=='{':
            stack.append(elem[i])
            stack.append(elem[i+1])
            sol+=1
        elif elem[i]=='}' and elem[i+1]=='{':
            if len(stack)!=0:
                if stack[-1]=='{':
                    stack.pop()
                    stack.append(elem[i+1])

                else:
                    stack.append(elem[i])
                    stack.append(elem[i+1])
                    sol+=1
            else:  
                stack.append(elem[i])
            ``  stack.append(elem[i+1])
                sol+=2
        elif elem[i]=='}' and elem[i+1]=='}':
            if len(stack)!=0:
                if stack[-1]=='{' and stack[-2]=='{':
                    stack.pop()
                    stack.pop()
                    sol-=1
                elif stack[-1]=='{' and stack[-2]=='}':
                    stack.pop()
                    stack.append(elem[i+1])
                else:
                    stack.append(elem[i])
                    stack.append(elem[i+1])
                    sol+=1
            else:
                stack.append(elem[i])
                stack.append(elem[i+1])
                sol+=1
        i+=2
    print(sol)

....
预期5产出6

disbfnqx

disbfnqx1#

我已经尝试根据字符串表达式所需的左括号和反转的数量来解决您的问题,以计算括号反转的最小数量。
下面给出了相同的Python代码:

def cal_rev(exp):
    if len(exp) % 2:
        return -1
    open = 0
    invert = 0
    for i in exp:
        if i == '{':
            open += 1
        else:
            if open:
                open -= 1
            else:
                open = 1
                invert += 1
    print(invert + open/2)

if __name__ == '__main__':
    expr = "}{}{}{}}}{{{{{}{}{}}{{}{}{}}{{}}{{"
    cal_rev(expr)
ozxc1zmp

ozxc1zmp2#

使用Python

def countBracketReversals(string):
    if(len(string) == 0):
        return 0
    if(len(string)%2 != 0):
        return -1
    s = []
    for char in string:
        if char == '{':
            s.append(char)
        else:
            if(len(s) > 0 and s[-1] == '{'):
                s.pop()
            else:
                s.append(char)
    count = 0
    while(len(s) != 0):
        c1 = s.pop()
        c2 = s.pop()
        if c1!=c2:
            count+=2
        else:
            count+=1
    return count
string = input()
ans = countBracketReversals(string)
print(ans)

产出

}{}{}{}}}{{{{{}{}{}}{{}{}{}}{{}}{{
5

链接:https://www.svastikkka.com/2022/07/minimum-bracket-reversal.html

kpbpu008

kpbpu0083#

你可以使用link找到你问题的答案,这个链接提供了不同的方法来解决上面的问题,还有c,java和python代码。
链接中使用的最佳方法很简单,包括以下步骤。
1.在第一次遍历时删除字符串的平衡部分,只在堆栈中保留不平衡部分。
1.那么堆栈中只剩下类型为}}} ...}{... {{{的字符串。
1.设}的计数为m,{的计数为n。
1.最小逆转次数为ceil(m/2)+ceil(n/2)。
Python代码如下:

def countMinReversals(expr):  

    lenn = len(expr)  

    # length of expression must be even  
    # to make it balanced by using reversals.  
    if (lenn % 2) : 
        return -1

    # After this loop, stack contains  
    # unbalanced part of expression,   
    # i.e., expression of the form "...."  
    s = []  
    for i in range(lenn): 
        if (expr[i] =='' and len(s)):  

            if (s[0] == '') : 
                s.pop(0)  
            else: 
                s.insert(0, expr[i])  
        else: 
            s.insert(0, expr[i])  

    # Length of the reduced expression  
    # red_len = (m+n)  
    red_len = len(s)  

    # count opening brackets at the  
    # end of stack  
    n = 0
    while (len(s)and s[0] == '') : 
            s.pop(0)  
            n += 1

    # return ceil(m/2) + ceil(n/2) which 
    # is actually equal to (m+n)/2 + n%2  
    # when m+n is even.  
    return (red_len // 2 + n % 2)

时间复杂度:时间复杂度O(n)
好好享受吧!

相关问题