括号匹配问题

不羁岁月 提交于 2020-02-04 22:13:12

括号匹配问题

堆栈存入数组下标间接实现数组元素的操作

不使用堆栈

#include<iostream>
#include<string>

using namespace std;

bool find(string& s, int index) {
	while (index > 0) {
		index--;
		if (s[index] == '(') {
			s[index] = 'a';
			return true;
		}
	}
	return false;
}
int main() {
	string data;
	while (cin >> data) {
		cout << data << endl;
		for (int i = 0;i < data.length();i++) {
			if (data[i] == ')') {
				if (find(data, i)) {
					data[i] = 'a';
				}
			}
		}
		for (int i = 0;i < data.length();i++) {
			if (data[i] == '(') {
				cout << "$";
			}
			else if (data[i] == ')') {
				cout << "?";
			}
			else {
				cout << " ";
			}
		}
		cout << endl;
	}
	return 0;
}

使用堆栈

#include <stdio.h>
#include <stack>
using namespace std; 
stack<int> S; 
char str[110]; 
char ans[110]; 
int main () { 
	while (scanf ("%s",str) != EOF) { 
		int i; 
		for (i = 0;str[i] != 0;i ++) { 
			if (str[i] == '(') { 
				S.push(i); 
				ans[i] = ' ';
			} 
			else if (str[i] == ')') { 
				if (S.empty() == false) { 
					S.pop(); 
					ans[i] = ' '; 
				} 
				else ans[i] = '?'; 
			} 
			else ans[i] = ' ';
		} 
		while(!S.empty()) { 
			ans[ S.top() ] = '$'; 
			S.pop(); 
		} 
		ans[i] = 0;
		puts(str); 
		puts(ans); 
	} 
	return 0; 
}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!