括号是否平衡!在C ++中

时间:2014-03-03 16:55:53

标签: c++ josephus

我在检查括号字符串是否平衡的算法方面遇到了一些问题。我必须从文本文件中获取输入并在另一个文本文件中显示输出。我遇到了麻烦algorithm.Please帮我找出问题

#include <iostream>
#include <string.h>
#include <fstream>
#include "stack.h"
#include "stack.cpp"
using namespace std;
int main() {
  StackType<char> c;
  ifstream inFile("parentheses.txt");
  ofstream outFile("report.txt");
  int i, N;
  char str[500];
  inFile >> N;
  inFile >> str;
  while (str[i]) {
    for (int i = 0; str[i] != '\0'; i++) {
      if ((str[i] == '(') || (str[i] == '{') || (str[i] == '[')) {
        c.Push(str[i]);
      } else if ((str[i] == ')') || str[i] == '}' || str[i] == ']') {
        if (c.isEmpty() == 1)
          outFile << "Parentheses are not Balanced" << endl;
        else if ((str[i] == ')' && str[i] == '(') ||
                 (str[i] == '}' && str[i] == '{') ||
                 (str[i] == ']' && str[i] == '[')) {
          c.Pop();
        } else
          outFile << "Parentheses are not Balanced" << endl;
      }
    }
    i++;
  }
  if (c.isEmpty() == 1)
    outFile << "Parentheses are Balanced" << endl;
  else
    outFile << "Parentheses are not Balanced" << endl;
}

2 个答案:

答案 0 :(得分:1)

我可以肯定地说:

if((str[i] == ')' && str[i]  == '(') || (str[i] == '}' && str[i] == '{') || (str[i] == ']' && str[i] == '['))

不正确,因为它总是错误的。我假设你的意思是:

if ((c.Top() == '(' && str[i] == ')' || ...)

答案 1 :(得分:0)

您的代码目前永远不会调用'Pop',因为您将str [i]与其自身进行比较,期望它是两个不同的值。

相反,你应该将stri [i]与堆栈顶部的任何内容进行比较。