标签:
算法
1 从第一个字符开始扫描
2 当遇见普通字符时候忽略,遇见做字符压入栈。
3 当遇见右符号时候从栈中弹出栈顶符号
匹配成功,继续读入下一字符
匹配失败,立即停止并报错
成功:所有字符扫描完毕,且栈为空
失败:匹配失败或者所有字符扫描完毕但栈不是空的。
伪代码:
int scanner(const char* code)
{
创建栈;
int i = 0;
while( code[i] != ‘\0‘ )
{
if( 左符号)
{
进栈;
}
if( 右符号 )
{
将右符号读取出来
if( (c与code[i] 不匹配或者c为空)
{
报错,听着循环
}
}
i++;
}
if( (判断是否匹配完成,而且栈是空的)
{
printf("Succeed!\n");
ret = 1;
}
else
{
printf("Invalid code!\n");
ret = 0;
}
消除栈
return ret;
}
代码
int scanner(const char* code)
{
LinkStack* stack = LinkStack_Create(); //创建一个栈
int ret = 0;
int i = 0;
while( code[i] != ‘\0‘ ) //判断有没有走到最后
{
if( isLeft(code[i]) ) //如果是左符号,进栈
{
LinkStack_Push(stack, (void*)(code + i));
}
if( isRight(code[i]) ) //如果是右符号
{
char* c = (char*)LinkStack_Pop(stack);
//将符号出栈,然后赋值给一个char变量
if( (c == NULL) || !match(*c, code[i]) )//c与code[i] 不匹配或者c为空
{
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); //清空
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;
}
标签:
原文地址:http://blog.csdn.net/sky_caicai/article/details/46405977