Topic links
Experimental two-bracket matching judgment algorithm
Time Limit: 1000MS |
|
Memory Limit: 65536K |
Total Submissions: 2202 |
|
Accepted: 924 |
Description
Assume that the correct format is in the expression ([] ()) or [([]]), or both [(]) or ([)] or (()]) are in an incorrect format. A stack-based design algorithm that determines if the parentheses match correctly.
Input
The input data has multiple groups, one row per set of test data, a string containing only ' [', '] ', ' (', ') '.
Output
For each set of test data, output No if the brackets match the output yes.
Sample Input [] () [] ([[]]) [)
Sample Output Yes No
The following:
Use stack to determine storage. Scan the string from beginning to end, if the opening parenthesis (either small or medium) are stacked. If the right parenthesis, the current character and the stack of the head element, if the pairing on the stack jump out of the head element, if not paired, then you can set the flag flag to 0. If it is a closing parenthesis and there are no elements inside the stack, flag can also be 0. If the scan is complete and there are still elements inside the stack, flag is also 0.
OJ reason multiple groups of inputs cannot be used with ~scanf ("")
#include <iostream> #include <stdio.h> #include <map> #include <queue> #include <string.h
> #include <string> #include <stack> using namespace std;
typedef long Long LL;
int main () {char s[10005];
stack<char>st;
while (scanf ("%s", s)!=eof) {while (!st.empty ()) St.pop ();
int Len=strlen (s), flag=1; for (int i=0;i<len;i++) {if (s[i]== ' | | |
s[i]== ' [') St.push (S[i]);
else{if (St.empty ()) {flag=0;break;
} char tmp=st.top ();
St.pop ();
if (s[i]== ') ' &&tmp== ' [') {flag=0;
Break
} else if (s[i]== '] ' &&tmp== ' (') {flag=0;
Break
}}} if (!st.empty ()) flag=0;
if (flag) printf ("yes\n"); else printf ("no\n");
} return 0;
}