问题描述
功能是计算括号的深度,并返回最大和最早深度的位置。
enter code here
#include<iostream>
#include<string.h>
using namespace std;
int main() {
int n = 0,i =0,count = 0,maxi = 0,index = 0;
string str;
cout << "Enter n";
cin >> n;
cout << "Enter the brackets";
cin >> str;
while (n--) {
for (i = 0; i < n; i++) {
if (str[i] == 1) {
count = 0;
while (str[i] != 2) {
count++;
i++;
}
if (count > maxi) {
maxi = count;
index = i - count;
}
}
}
}
cout << "depth= " << maxi << endl << "starting index=" << index;
return 0;
}
//不知道逻辑出了什么问题..我计算了开括号,一旦出现闭括号,计数就停止了,索引号。并且计数通过了。 PS 1 表示开括号,2 表示闭括号。
解决方法
我很难理解你的逻辑,因此跳入我自己的一些解释。
- 我将
n
设为要输入的字符串数。 - 每个字符串使用
str.size()
来获取测试的长度。 - 将“1”更改为“”,认为您正在找到
<..>
之间的长度。 - 把输出移到while循环
n
里面,为了方便观察,可以把这行放到程序末尾。它不会改变执行。
我改成的代码:
#include<iostream>
#include<string>
using namespace std;
int main() {
int n = 0,i =0,count = 0,maxi = 0,index = 0;
string str;
char bra='<',key='>'; // change the delimiters
cout << "Enter test runs : n = ";
cin >> n; // assume n the number of test runs
while (n--)
{
cout << "Enter the brackets : ";
cin >> str;
for (i = 0; i < str.size(); i++) { //use str.size();
if (str[i] == bra) {
count = 0;
while (str[++i] != key) { count++; }
if (count > maxi) {
maxi = count;
index = i - count;
}
}
}
cout << "depth= " << maxi << endl << "starting index = " << index <<std::endl;
}
return 0;
}
测试:
$ ./a.exe
Enter test runs : n = 2
Enter the brackets : First<1234>second<1234567>end1
depth= 7
starting index = 18
Enter the brackets : Thrid<123456789>forth<12345>end2
depth= 9
starting index = 6