测试代码
#include "stdafx.h"
#include <cstdlib>
#include <iostream>
#include <string>
#include <stack>
using std::cout;
using std::cin;
using std::endl;
using std::stack;
using std::string;
int CalculateMaxMatch(string inputStr);
int main()
{
string inputStr;
cout << "请输入括号的字符串: ";
cin >> inputStr;
cout << "当前输入的括号字符串: " << inputStr << endl;
cout << "最长括号匹配是: " << CalculateMaxMatch(inputStr) << endl;
system("pause");
return 0;
}
int CalculateMaxMatch(string inputStr) {
int length = inputStr.length();
stack<int> stack;
int max = 0;
int start = -1;
for (int i = 0; i < length; i++) {
char c = inputStr.at(i);
if (c == '(') {
stack.push(i);
}
else {
if (!stack.empty()) {
stack.pop();
if (stack.empty()) {
if (max < i - start)
max = i - start;
}
else {
int t = stack.top();
if (max < i - t)
max = i - t;
}
}
else {
start = i;
}
}
}
return max;
}
测试结果