我有一个问题来完成这个 R 代码。我们得到一个带有如下括号的字符串“( ((X)) (((Y))) )” 我们需要找到平衡括号的最大深度,如上例中的 4。由于“Y”被 4 个平衡括号包围。
如果括号不平衡,则返回 -1 我的代码如下所示:
current_max = 0
max = 0
def = function (S){
n=S
for (i in nchar(n))
if (is.element('(',n[i]))
{
current_max <- current_max + 1
}
if (current_max > max)
{
max <- current_max
}
else if (is.element(')',n[i]))
{
if (current_max > 0)
{
current_max <- current_max - 1
}
else
{
return -1
}
}
if (current_max != 0)
{
return -1
}
return (max)
}
Run Code Online (Sandbox Code Playgroud)
但是当我调用函数 def("(A((B)))") …