标签匹配学习小记 Hdu3351&Poj3991 + SGU302

来源:互联网 发布:全文期刊数据库 编辑:程序博客网 时间:2024/06/05 18:56

最近碰到了标签匹配问题,我的两边同时处理的算法果断坑了……网上也没有找到太多题用来练。。。

以下基本思想转自:http://blog.csdn.net/niushuai666/article/details/6632614

1. 括号匹配的四种可能性:
①左右括号配对次序不正确
②右括号多于左括号
③左括号多于右括号
④左右括号匹配正确

2. 算法思想:
1.顺序扫描算数表达式(表现为一个字符串),当遇到三种类型的左括号时候让该括号进栈;
2.当扫描到某一种类型的右括号时,比较当前栈顶元素是否与之匹配,若匹配,退栈继续判断;
3.若当前栈顶元素与当前扫描的括号不匹配,则左右括号配对次序不正确,匹配失败,直接退出;
4.若字符串当前为某种类型的右括号而堆栈已经空,则右括号多于左括号,匹配失败,直接退出;
5.字符串循环扫描结束时,若堆栈非空(即堆栈尚有某种类型的左括号),则说明左括号多于右括号,匹配失败;

6.正常结束则括号匹配正确。


做了两道题,贴代码

Hdu3351&Poj3991

#include <cstdio>char str[2010];int main (){    int cas=1;    while (scanf("%s",str) && str[0]!='-'){int ans=0,lef=0;for (int i=0;str[i]!='\0';i++)if (str[i]=='{')lef++;else if (lef>0)lef--;elseans++,lef++;//注意All sequences are of even length. 字母数一定为偶数printf("%d. %d\n",cas++,ans+lef/2);}return 0;}

SGU302

遇到的就是这题,当时参考了:http://www.cppblog.com/willing/archive/2010/05/11/115109.html

#include <cstdio>#include <cctype>#include <stack>using namespace std;char s[1005];stack <bool> sta;int main (){int i=0;scanf ("%s",s);while (s[i])if (s[i]=='<' && s[i+1]!='/')if (s[i+1] == 'U')                sta.push (false),i+=4;else                sta.push(true),i+=6;else if (s[i] == '<'){if (s[i+2] == 'U')i+=5;elsei+=7;sta.pop();}else            if (sta.empty())printf("%c",s[i++]);else if (sta.top())                printf("%c",tolower(s[i++]));else                printf("%c",toupper(s[i++]));printf("\n");    return 0;}


原创粉丝点击