Exercise2
This commit is contained in:
43
Exercise/Homework2/Q1.cpp
Normal file
43
Exercise/Homework2/Q1.cpp
Normal file
@@ -0,0 +1,43 @@
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
using namespace std;
|
||||
|
||||
int map(char c) {
|
||||
if (c == '{') return 4;
|
||||
if (c == '[') return 3;
|
||||
if (c == '(') return 2;
|
||||
if (c == '<') return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool match(char a, char b) {
|
||||
return (a == '(' && b == ')') || (a == '[' && b == ']') || (a == '{' && b == '}') || (a == '<' && b == '>');
|
||||
}
|
||||
|
||||
bool check(const string& s) {
|
||||
string front;
|
||||
for (int i = 0; i < s.size(); i++) {
|
||||
if (s[i] == '{' || s[i] == '[' || s[i] == '(' || s[i] == '<') {
|
||||
if (!front.empty() && map(front.back()) <= map(s[i]))
|
||||
return false;
|
||||
front.push_back(s[i]);
|
||||
} else if (s[i] == '}' || s[i] == ']' || s[i] == ')' || s[i] == '>') {
|
||||
if (front.empty() || !match(front.back(), s[i]))
|
||||
return false;
|
||||
front.pop_back();
|
||||
}
|
||||
}
|
||||
return front.empty();
|
||||
}
|
||||
|
||||
int main() {
|
||||
int n;
|
||||
cin >> n;
|
||||
for (int i = 0; i < n; i++) {
|
||||
string s;
|
||||
cin >> s;
|
||||
cout << (check(s) ? "Match" : "Fail") << endl;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user