OJ Brush Question Record: Determine whether the brackets in a string match question number: 616

Determine whether the brackets in a string match the question number: 616

Subject requirements:

Read a character string from the keyboard, which contains only () {} [], and judge whether each kind of parenthesis in the character string appears in pairs.

Tip: It can be achieved with the help of a stack. The parentheses must appear in pairs, such as ()[ ]{}, which are matched parentheses, such as ([{])}, which are unmatched parentheses (no spaces in between).

Enter description

Enter a string (no spaces in between)

Output description

Match output yes, otherwise output no

Input sample

(([{}]))

Sample output

yes

Problem-solving ideas:
using stacks can solve this problem very cleverly. Traverse the string, if the character is a left parenthesis, put this character on the stack, if it is a right parenthesis, pop a character from the stack, and judge whether the popped character is the corresponding left parenthesis, if it is, continue to traverse, if not , The brackets do not match, exit the loop, and return the judgment result. After the loop ends, yes or no is output according to the judgment result.

Customs clearance code:

#include <iostream>

#define MaxSize 100

using namespace std;

class Matcher {
    
    
	public:
		Matcher();
		
	public:
		void Push(char ch);
		char Pop();
		bool isEmpty();		
		bool Match(string str);
		
	private:
		char arr_[MaxSize];
		int top_;
};

Matcher::Matcher() {
    
    
	top_ = -1;
}

void Matcher::Push(char ch) {
    
    
	if (top_ == MaxSize) throw "上溢";
	
	arr_[++top_] = ch;
}

char Matcher::Pop() {
    
    
	if (top_ < 0) throw "None";
	
	char res = arr_[top_];
	top_--;
	
	return res;
}

bool Matcher::isEmpty() {
    
    
	return top_ < 0 ? true : false;
}

bool Matcher::Match(string str) {
    
    
	int LEN = str.size();
	bool isMatch = true;
	
	for (int i = 0; i < LEN; i++) {
    
    
		if (str[i] == '(' || str[i] == '[' || str[i] == '{') {
    
    
			Push(str[i]);
		} else {
    
    
			
			if (str[i] == ')') {
    
    
				if (isEmpty() || Pop() != '(') {
    
    
					isMatch = false;
					break;
				}
			} else if (str[i] == ']') {
    
    
				if (isEmpty() || Pop() != '[') {
    
    
					isMatch = false;
					break;
				}
			} else if (str[i] = '}') {
    
    
				if (isEmpty() || Pop() != '{') {
    
    
					isMatch = false;
					break;
				}
			}
			
		}
	}
	
	return isMatch;
} 

int main() {
    
    
	Matcher m;
	string str;
	
	cin >> str;
	
	cout << (m.Match(str) ? "yes" : "no");
	
	return 0;
}

complete.

Guess you like

Origin blog.csdn.net/weixin_45711556/article/details/108829002