poj 括号匹配问题

时间:2023-01-05 18:53:20
#include <iostream>
#include <cstdio>
#include <string.h>
using namespace std;
void m(char s[], int flag[], int n) {//匹配函数
	if (strlen(s) != n) { 
		if (s[n] != ')') m(s, flag, n + 1);//找到‘)’
		else{
			int i = n - 1;
			while (i >= 0 && (s[i] != '(' || flag[i] == 1)) i--;//找最近的‘(’
			if (i != -1 && s[i] == '(' && flag[i] == 0) {//匹配成功
				flag[i] = 1;
				flag[n] = 1;
			}
			m(s, flag, n + 1);//接着匹配
		}
	}
}
int main() {
	char s[100];
	while (cin.getline(s, 101)) {
		int flag[100] = {0};//匹配标志
		m(s, flag, 0);
	    cout << s<<endl;
		for (int i = 0; i < strlen(s); i++) {//根据匹配结果输出
			if (flag[i] == 0) {
				if (s[i] == '(') cout << '$';
				else if (s[i] == ')') cout << '?';
				else cout << ' ';
			}
			else
				cout << ' ';
		}
		cout << endl;
	}
	return 0;
}