As we all know, there are many interesting (H) games in kennethsnow’s computer. But he sets a password for those games. Zplinti1 wants to crack his password and play those games.
Kennethsnow uses only 6 kinds of characters to form his password:
- brackets:
(
and)
- square brackets:
[
and]
- curly brackets:
{
and}
Kennethsnow’s password must be a correct bracket sequence, and will not be empty.
Zplinti1 found a string written by kennethsnow, and he is sure that kennethsnow’s password is a substring of that, he wonders the maximum possible length of his password, or if his judgment is wrong.
Please note that the original string may also be the password.
Input
The first line of input contains a number T, indicating the number of test cases. (T≤30) For each case, there is a string s, which is the string zplinti1 found. (1≤|s|≤1,000,000, the string will contain those 6 kinds of characters only)
Output
For each case, output Case #i:
first. (i is the number of the test case, from 1 to T). If zplinti1’s judgment is wrong (i.e. the answer is 0), output I think H is wrong!
, otherwise output a single number, indicating the maximum possible length of kennethsnow’s password.
Sample input and output
Sample Input | Sample Output |
---|---|
3 (){[]} {([(])} ))[{}]] |
Case #1: 6 Case #2: I think H is wrong! Case #3: 4 |
Hint
We can define a correct bracket sequence
more precisely in this way:
Strings ()
, []
, and {}
are correct.
For each correct sequence A
, (A)
, [A]
, {A}
is also correct.
For each correct sequence A
and B
, AB
is also correct.
解题报告:
栈的简单应用题~,从左到右扫一遍,属于合法序列的flag标记打上,之后再扫一次,确认最长的连续合法长度
#include <iostream> #include <algorithm> #include <cstring> const int maxn = 1000000 + 50; using namespace std; char s[maxn]; int pos[maxn]; bool flag[maxn]; bool match(char s1,char s2) { if (s1 == '(' && s2 != ')') return false; else if (s1 == '[' && s2 != ']') return false; else if (s1 == '{' && s2 != '}') return false; return true; } int main(int argc , char * argv[]) { int Case,T=1; scanf("%d",&Case); while(Case--) { scanf("%s",s); int top = 0 , ans = 0 , len = strlen(s), pt = 0; memset(flag,false,sizeof(flag)); for(int i = 0 ; i < len ; ++ i) { if (s[i] == '(' || s[i] == '[' || s[i] == '{') pos[top++] = i; else if (top > 0) { int tpos = pos[--top]; char ts = s[tpos]; if (match(ts,s[i])) { flag[tpos] = true; flag[i] = true; } else top = 0; } } for(int i = 0 ; i < len ; ++ i) if (!flag[i]) { ans = max(ans,pt); pt = 0; } else pt++; ans = max(ans,pt); printf("Case #%d: ",T++); if (ans) printf("%d ",ans); else printf("I think H is wrong! "); } return 0; }