nyoj2-括号配对问题

题目链接

##### 思路

括号 配对问题是一个典型的堆栈问题,对于每一个右括号,与之配对的左括号必然是之前所有未配对的左括号中的最右边一个;因此我们将字符串从左到右扫描,当出现左括号时,将其加入栈中;当出现右括号时,我们判断栈顶的括号是否与当前的右括号配对;

#####code

#include <string>
#include <iostream>
#include <stack>
#include <cstdio>
using namespace std;
int main() {
  std::ios::sync_with_stdio(false);
  std::cin.tie(0);
  string s;
  int n;
  cin >> n;
  while(n --) {
    cin >> s;
    stack<char> st;
    int l = s.size();
    bool ok = true;
    for(int i = 0; i < l; ++ i) {
	  if(s[i] == '(' || s[i] == '[') {   //出现左括号时加入栈
	    st.push(s[i]);
	  }
	  else {
	  //判断是否能配对
	    if(!st.empty() && ((s[i] == ']' && st.top()=='[') || (s[i] == ')' && st.top()=='('))) {
		  st.pop();	
	    }
	    else {
		  ok = false;
		  break;
	    }
	  }
    }
    if(ok && st.empty()) {
      puts("Yes");
    }
    else {
      puts("No");
    }
  }
  return 0;
}

 

  

原文地址:https://www.cnblogs.com/topk/p/6580070.html