【问题标题】:Tried counting depth of brackets using array and not stack尝试使用数组而不是堆栈计算括号的深度
【发布时间】:2021-04-27 15:07:11
【问题描述】:

函数是计算括号的深度,返回最大深度和最早深度的位置。

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?其次,您在调试方面做了哪些努力?您是否尝试过使用 调试器 在监控变量及其值的同时逐条执行代码语句?
  • 字符串将完全等于'n'。我习惯于视觉工作室,所以它会告诉所有警告和错误。它是一个实时编译器。它只是给了我错误的输出
  • str[i] == 1 这样的比较没有意义。 str字符的字符串。据说是一串“括号”字符而不是数字字符。 while (n--) 呢?如果 n 应该是字符串的长度,这有什么意义?整个算法似乎都不对了。
  • 是否允许使用不同类型的括号?如果不是,为什么需要数据结构? (只需跟踪当前打开的括号和当前的“最佳匹配”。如果遇到左括号,增加括号计数,如果遇到右括号,更新最佳匹配(如有必要),并减少括号计数。 ..

标签: c++ arrays stack brackets dsa


【解决方案1】:

我很难理解你的逻辑,因此跳入我自己的一些解释。

  • 我将n 设为要输入的字符串数。
  • 每个字符串使用str.size() 来获取长度进行测试。
  • 将“1”更改为“”,认为您正在查找 &lt;..&gt; 之间的长度。
  • 将输出移到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

【讨论】:

    猜你喜欢
    • 2020-07-01
    • 1970-01-01
    • 2015-06-06
    • 2022-01-02
    • 2014-05-13
    相关资源
    最近更新 更多