给定一个数字N ,任务是将最小数量的左括号和右括号插入数字N 中,使得结果字符串是平衡的,并且每个数字D都恰好在D对匹配括号中。
例子:
Input: N = 312
Output: (((3))1(2))
Explanation:
Every digit in the number is within exactly in D parenthesis.
There are other possible strings like (((3)))(1)((2)) but the string obtained is the string that can be formed with the minimum number of parenthesis.
Input: N = 111000
Output: (111)000
Explanation:
Every digit in the number is within exactly D parenthesis.
There are other possible strings like (1)(1)(1)000, (11)(1)000 but the string obtained is the string that can be formed with the minimum number of parenthesis.
做法:思路是用一个数组来记录需要添加的括号个数。
对于任何数字,只能通过将数字嵌套在括号内来添加最小括号数。
例如:让 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 Classes Live