算法
算法:
-遇到普通字符忽略
- 遇到左括号入栈
- 遇到右符号 从栈中弹出栈顶符号,比配
- 匹配成功,继续扫描
- 匹配失败,停止,报错
结束:
- 所有字符扫描完毕,栈为空:成功
- 匹配失败或扫描完毕,但是栈不为空:失败
代码
//
// Created by xuehu96 on 2019-08-09.
//
#include <stdio.h>
#include "../linkstack.h"
int isLeft(const char c)
{
int ret = 0;
switch(c)
{
case '(':
case '<':
case '[':
case '{':
case '\'':
case '\"':
ret = 1;
break;
default:
ret = 0;
}
return ret;
}
int isRight(const char c)
{
int ret = 0;
switch(c)
{
case ')':
case '>':
case ']':
case '}':
case '\'':
case '\"':
ret = 1;
break;
default:
ret = 0;
}
return ret;
}
int match(const char left, const char right)
{
switch(left)
{
case '(':
return (right == ')');
case '<':
return (right == '>');
case '[':
return (right == ']');
case '{':
return (right == '}');
case '\'':
return (right == '\'');
case '\"':
return (right == '\"');
default:
return 0;
}
}
void matchErr(const char *str, int pos)
{
printf ("Error: braces does not match at position: %d \n", pos);
printf ("%s\n", str);
for(int i = 0; i < pos; ++i)
{
printf (" ");
}
printf ("^\n");
}
int scanner(const char *code)
{
int i = 0,ret = 0;
LinkStack *stack = NULL;
stack = LinkStack_Create ();
while(code[i] != '\0')
{
if(isLeft (code[i]))
{
LinkStack_Push (stack, (void *) &code[i]);
}
if(isRight (code[i]))
{
if(LinkStack_Size (stack) == 0)
{
matchErr (code, i);
LinkStack_Destroy (stack);
return 0;
}
char *tmp = (char *) LinkStack_Pop (stack);
if((!match (*tmp, code[i])) || (tmp == NULL))
{
matchErr (code, i);
LinkStack_Destroy (stack);
return 0;
}
}
i++;
}
if(code[i] == '\0' && LinkStack_Size (stack) == 0)
{
ret = 1;
}
else if(LinkStack_Size (stack) != 0)
{
matchErr (code, i);
ret = 0;
}
else
{
printf ("Fail match:err\n");
}
LinkStack_Destroy (stack);
return ret;
}
/*算法:
* 遇到普通字符忽略
* 遇到左括号入栈
* 遇到右符号 从栈中弹出栈顶符号,比配
* 匹配成功,继续扫描
* 匹配失败,停止,报错
* 结束:
* 所有字符扫描完毕,栈为空:成功
* 匹配失败或扫描完毕,但是栈不为空:失败
* */
int demo_matchingSymbol()
{
//const char *code = "#include stdio.h> int main(){int a[4][4]; int (*p)4[];p = a[0]; return 0;}";
const char *code = "typedef struct M { int B ; int C; unsigned int ** D ; } A;L* SeqList_Create\n";
if(scanner (code))
{
printf ("success\n");
}
return 0;
}