Sicily-brackets matching
简要思路:利用栈存储括号(分小括号,中括号,大括号),如果是左括号就push进栈;如果是右括号且top是相应的左括号,就pop了。到最后遍历完整个字符串,如果这个栈是空的,说明所有的括号都匹配了。
下面上代码。
1 #include <iostream> 2 #include <cstring> 3 #include <string> 4 #include <stack> 5 using namespace std; 6 7 int main() { 8 int T; 9 cin >> T; 10 while(T--) { 11 int count = 0; 12 string str; 13 cin >> str; 14 int size = str.length(); 15 stack<char> temp; 16 for (int i = 0; i < size; i++) { 17 if (str[i] == '(' || str[i] == '[' || str[i] == '{') { 18 temp.push(str[i]); 19 } else { 20 if (str[i] == ')') { 21 if (!temp.empty() && temp.top() == '(') { 22 temp.pop(); 23 } else { 24 cout << "No" << endl; 25 count = 1; 26 break; 27 } 28 } 29 if (str[i] == '}') { 30 if (!temp.empty() && temp.top() == '{') { 31 temp.pop(); 32 } else { 33 cout << "No" << endl; 34 count = 1; 35 break; 36 } 37 } 38 if (str[i] == ']') { 39 if (!temp.empty() && temp.top() == '[') { 40 temp.pop(); 41 } else { 42 cout << "No" << endl; 43 count = 1; 44 break; 45 } 46 } 47 } 48 } 49 if (count == 0) { 50 if (temp.empty() == true) { 51 cout << "Yes" << endl; 52 } else { 53 cout << "No" << endl; 54 } 55 } 56 57 } 58 return 0; 59 }
-