#include using namespace std; void set_max(int& a,int b){ a = max(a,b); } int DP[1001][1001]; bool mozem(char x, string b){ for(auto y : b){ if(x == y) return 1; if(y == '?') return 1; } return 0; } int main() { int n; cin>>n; string s; cin>>s; int m; cin >>m; string pattern; cin >>pattern; vector pat; vector> trans(m); vector stak; int last = -1; bool hran = false; for(int i = 0;i < m;i++){ char p = pattern[i]; if(p == '('){ stak.push_back(pat.size()); }else if(p == ')'){ last = stak.back(); stak.pop_back(); }else if(p == '*'){ if(pattern[i-1] == ')'){ trans[pat.size()-1].push_back(last); trans[last].push_back(pat.size()); }else { trans[pat.size()-1].push_back(pat.size()-1); trans[pat.size()-1].push_back(pat.size()); } }else if(p == '['){ pat.push_back({}); hran = true; }else if(p ==']'){ hran = false; }else{ if(hran){ pat.back().push_back(p); }else{ pat.push_back({p}); } } } int N = n, M = pat.size(); for(int i = 0;i < N+1;i++)for(int j = 0;j < M+1;j++) DP[i][j] = INT_MIN; DP[0][0] = 0; for(int i = 0; i < N+1;i++)for(int j = 0;j < M+1;j++){ if(i != N && j != M) if(mozem(s[i], pat[j])){ for(int x : trans[j])if(x <= j){ set_max(DP[i+1][x], DP[i][j] + 1); } set_max(DP[i+1][j+1], DP[i][j] + 1); } if(j != M){ for(int x : trans[j])if(x > j){ set_max(DP[i][x], DP[i][j]); } } if(i != N) set_max(DP[i+1][j], DP[i][j]); } if(DP[N][M] < 0) cout << -1 << endl; else cout << DP[N][M] << endl; }