Stack application --- compiler symbol match, --- compiler symbol
Algorithm
1 scan from the first character
2. Ignore common characters and press the characters into the stack.
3. The stack top symbol pops up from the stack when the right symbol is met.
Matched successfully. Continue to read the next character
An error occurred while matching. Stop immediately and report an error.
Success: All characters are scanned and the stack is empty.
Failed: the matching fails or all characters have been scanned but the stack is not empty.
Pseudocode:
Int substring (const char * code)
{
Create a stack;
Int I = 0;
While (code [I]! = '\ 0 ')
{
If (left)
{
Stack;
}
If (right sign)
{
Read the right symbol
If (c and code [I] do not match or c is empty)
{
Error reported. Listen to the loop
}
}
I ++;
}
If (determine whether the matching is complete, and the stack is empty)
{
Printf ("Succeed! \ N ");
Ret = 1;
}
Else
{
Printf ("Invalid code! \ N ");
Ret = 0;
}
Eliminate Stack
Return ret;
}
Code
Int substring (const char * code)
{
LinkStack * stack = LinkStack_Create (); // create a stack
Int ret = 0;
Int I = 0;
While (code [I]! = '\ 0') // determines whether it has reached the end
{
If (isLeft (code [I]) // if it is a left symbol
{
LinkStack_Push (stack, (void *) (code + I ));
}
If (isRight (code [I]) // if it is a right symbol
{
Char * c = (char *) LinkStack_Pop (stack); // exit the symbol from the stack and assign it to a char variable.
If (c = NULL) |! Match (* c, code [I]) // c does not match code [I] or c is empty
{
Printf ("% c does not match! \ N ", code [I]);
Ret = 0;
Break;
}
}
I ++;
}
If (LinkStack_Size (stack) = 0) & (code [I] = '\ 0 '))
{
Printf ("Succeed! \ N ");
Ret = 1;
}
Else
{
Printf ("Invalid code! \ N ");
Ret = 0;
}
LinkStack_Destroy (stack); // clear
Return ret;
}
Int isLeft (char c)
{
Int ret = 0;
Switch (c)
{
Case '<':
Case '(':
Case '[':
Case '{':
Case '\'':
Case '\"':
Ret = 1;
Break;
Default:
Ret = 0;
Break;
}
Return ret;
}
Int isRight (char c)
{
Int ret = 0;
Switch (c)
{
Case '> ':
Case ')':
Case ']':
Case '}':
Case '\'':
Case '\"':
Ret = 1;
Break;
Default:
Ret = 0;
Break;
}
Return ret;
}
Int match (char left, char right)
{
Int ret = 0;
Switch (left)
{
Case '<':
Ret = (right = '> ');
Break;
Case '(':
Ret = (right = ')');
Break;
Case '[':
Ret = (right = ']');
Break;
Case '{':
Ret = (right = '}');
Break;
Case '\'':
Ret = (right = '\'');
Break;
Case '\"':
Ret = (right = '\"');
Break;
Default:
Ret = 0;
Break;
}
Return ret;
}