天天看点

P1241 括号序列

#include<iostream>
#include<cstring>
#include<algorithm>
#include<vector>
#include<stack>
using namespace std;
const int N = 2e5 + 10;


bool ok[N];
string s;
int n;
stack<int> st;
void solve() {
  cin >> s;
  n = s.size();
  for (int i = 0; i < n; i ++) {
    if (s[i] == ']') {
      if (st.empty()) continue;
      int k = st.top();
      if (s[k] == '[') {
        ok[k] = ok[i] = 1;
        st.pop();
      }
    }
    else if (s[i] == ')') {
        if (st.empty()) continue;
      int k = st.top();
      if (s[k] == '(') {
        ok[k] = ok[i] = 1;
        st.pop();
      }
    }
    else st.push(i);
  }
  for (int i = 0; i < n; i ++) {
    if (ok[i]) cout << s[i];
    else {
      if (s[i] == '(' || s[i] == ')') cout << "()";
      else cout << "[]";
    }
  }
}
int main() {
  solve();
  return 0;
}      

继续阅读