Javascript 如何在给定的括号字符串中查找节点和级别?
我有一个带括号的输入字符串,如下所示 [1][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][ 我需要找出可以创建多少节点([]),以及可以在字符串中安排多少父级和子级括号 示例:[[[[[[[]]][[[[[]]][[[[[[]]]]]节点数=16层数=6 我尝试了一种查找“[”,“]”的开始索引和结束索引的方法,并计算了它的数量。如果两者相等,则我将索引添加到count。求和得到节点数 但我一直在寻找水平Javascript 如何在给定的括号字符串中查找节点和级别?,javascript,c#,python,Javascript,C#,Python,我有一个带括号的输入字符串,如下所示 [1][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][ 我需要找出可以创建多少节点([]),以及可以在字符串中安排多少父级和子级括号 示例:[[[[[[[]]][[[[[]]][[[[[[]]]]]节点数=16层数=6 我尝试了一种查找“[”,“]
for(int i=0;i<sth.Length;i++)
{
if(sth[i]=='[')
{
count1++;
}
else
{
count2++;
}
if (count1 == count2)
{
numOfNodes += count1;
count1 = 0;
count2 = 0;
}
}
for(inti=0;i与其说是编程,不如说是算法,但一种简单的方法是使用如下步骤中的堆栈
创建一个索引
遍历字符串,对每个字符执行以下操作
- 如果当前字符为
[
则将一项推到索引中
- 如果字符为
]
,则弹出一个项目
- 在遍历期间保持索引的最大值
完成导线测量后,最大值表示标高。
以下是示例的c#
代码:
string sampple = "[[[[][[[]]]][][][[]]]][[[[][]]]]";
int levels = 0;
int index = 0;
foreach (char c in sampple)
{
if (c == '[')
index++;
if (c == ']')
index--;
if (index >= levels)
levels = index;
}
Console.WriteLine("Levels: " + levels);
哪些产出:
级别:6
它更多的是关于算法而不是编程,但一个简单的方法是使用堆栈,如下面的步骤
创建一个索引
遍历字符串,对每个字符执行以下操作
- 如果当前字符为
[
则将一项推到索引中
- 如果字符为
]
,则弹出一个项目
- 在遍历期间保持索引的最大值
完成导线测量后,最大值表示标高。
以下是示例的c#
代码:
string sampple = "[[[[][[[]]]][][][[]]]][[[[][]]]]";
int levels = 0;
int index = 0;
foreach (char c in sampple)
{
if (c == '[')
index++;
if (c == ']')
index--;
if (index >= levels)
levels = index;
}
Console.WriteLine("Levels: " + levels);
哪些产出:
级别:6
试试这个
const str=“[[[[[]]][[[]]]][[[[]]]][[[[]]]]]”;
const maxlevel=getMaxLevel(str);
const nodesLength=getNodesLength(str);
log(maxlevel,'level');
log(nodesLength,'nodes');
函数getMaxLevel(str){
常量arr=str.match(/\[+/g);
如果(arr){
arr.sort((a,b)=>b.length-a.length);
返回arr[0]。长度;
}
}
函数getNodesLength(str){
设计数器=0;
而(/\[\]/.test(str)){
计数器++;
str=str.replace(/\[\]/,“”);
}
返回计数器;
}
试试这个
const str=“[[[[[]]][[[]]]][[[[]]]][[[[]]]]]”;
const maxlevel=getMaxLevel(str);
const nodesLength=getNodesLength(str);
log(maxlevel,'level');
log(nodesLength,'nodes');
函数getMaxLevel(str){
常量arr=str.match(/\[+/g);
如果(arr){
arr.sort((a,b)=>b.length-a.length);
返回arr[0]。长度;
}
}
函数getNodesLength(str){
设计数器=0;
而(/\[\]/.test(str)){
计数器++;
str=str.replace(/\[\]/,“”);
}
返回计数器;
}
Hi,你能解释一下上面的代码吗?我指的是maxlevel部分。如果[count由regex计算,它是否总是正确的?基本上,它所做的是提取一组或多组“[”例如[”[[”,“[[”,“[”,“[”],并将数组从最高频率到最低频率进行排序“[”您好,您能解释一下上面的代码吗?我是指maxlevel部分。如果[count由正则表达式进行,它是否总是正确的?基本上,它所做的是提取一组或多组“[”例如[”[”,“[”,“[”,“[”])。它将简单地从最高频率到最低频率对数组进行排序“[”