📜  平衡括号中给定数字N

📅  最后修改于: 2021-06-26 08:51:20             🧑  作者: Mango

给定数字N ,任务是将最小数量的开括号和闭括号插入数字N ,以使结果字符串平衡,并且每个数字D都正好在D对匹配括号中。

例子:

方法:想法是使用数组来跟踪需要添加的括号的数量。

对于任何数字,只能通过将数字嵌套在括号内来添加最小括号数。

例如:让N = 321。

  • 最初,创建一个空数组A []。
  • 给定的数字以数字方式进行迭代。
  • 最初,在数组中添加D个开头括号以存储该数字。因此,对于数字3,在数组中添加了3个左括号。
  • 在下一次迭代中,该数字可以大于或小于前一个数字。如果下一个数字较小(如上述示例中的2),则将3 – 2 = 1括号括起来。
  • 同样,如果下一位数字更大,则将打开括号中的绝对差数。
  • 对给定数字N中的所有数字重复上述两个步骤。最后,获得的字符串以最小的括号形成。

下面是上述方法的实现:

# Python program to find the balanced
# parentheses using the given number
  
# Function to find the balanced 
# parentheses using the given number
def balance(m):
  
    # Making the list of the
    # given number
    m = [int(i) for i in m]
  
    # Empty list to store the 
    # parentheses
    n = []
      
    # Iterating through the 
    # digits of the number
    for i in m: 
          
        # Calculating the difference between
        # opening and closing braces for the 
        # digit
        if (n.count('(')-n.count(')'))<= i:
  
            # If the next digit is greater, 
            # then open the brackets
            while (n.count('(')-n.count(')')) != i:
                n.append('(')         
            n.append(i)     
              
        # Similarly, find the difference 
        # between opening and closing braces
        elif (n.count('(')-n.count(')'))>i:
  
            # If the next digit is smaller,
            # then close the brackets
            while (n.count('(')-n.count(')'))!= i:
                n.append(')')
            n.append(i) 
              
    # Finally, close the remaining brackets
    while (n.count('(')-n.count(')'))!= 0:
        n.append(')')
      
    # Returning the string
    return ''.join(map(str, n))
      
# Driver code
if __name__ == "__main__":
      
    N = 312
      
    print(balance(str(N)))
输出:
(((3))1(2))

时间复杂度: O(K 2 ) ,其中K是数字N的数字总和。

如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。