poj 3461Oulipo
2016-07-21 14:43
337 查看
题目链接:http://poj.org/problem?id=3461
统计字符串出现的次数
统计字符串出现的次数
#include<cstdio> #include<iostream> #include<algorithm> #include<math.h> #include<string.h> #include<vector> #include<queue> #include<iterator> #include<vector> #include<set> #define dinf 0x3f3f3f3f typedef long long ll; //const int Max=(1<<16)+10; using namespace std; #define SIZE 100000005 const int N = 100000005; int m_next ; char S ,T ; int slen, tlen; void getNext() { int j, k; j = 0; k = -1; m_next[0] = -1; while(j < tlen) if(k == -1 || T[j] == T[k]) m_next[++j] = ++k; else k = m_next[k]; } /* 返回模式串T在主串S中首次出现的位置 返回的位置是从0开始的。 */ int KMP_Index() { int i = 0, j = 0; getNext(); while(i < slen && j < tlen) { if(j == -1 || S[i] == T[j]) { i++; j++; } else j = m_next[j]; } if(j == tlen) return i - tlen+1; else return -1; } /* 返回模式串在主串S中出现的次数 */ int KMP_Count() { int ans = 0; int i, j = 0; if(slen == 1 && tlen == 1) { if(S[0] == T[0]) return 1; else return 0; } getNext(); for(i = 0; i < slen; i++) { while(j > 0 && S[i] != T[j]) j = m_next[j]; if(S[i] == T[j]) j++; if(j == tlen) { ans++; j = m_next[j]; } } return ans; } int main() { int TT; int i, cc; string str; cin>>TT; while(TT--) { getchar(); scanf("%s %s",&T,&S); slen = strlen(S); tlen = strlen(T); printf("%d\n",KMP_Count()); //cout<<"模式串T在主串S中首次出现的位置是: "<<KMP_Index()/2+1<<endl; //cout<<"模式串T在主串S中出现的次数为: "<<KMP_Count()<<endl; } return 0; }
相关文章推荐
- 三阶魔方教程
- ANDROID SHAPE画圆形背景实现圆形TextView
- 谈谈javascript的Function中那些隐藏的属性/方法:caller/callee/apply/call/bind
- Java学习之路:不走弯路,就是捷径
- 安卓多线程之异步任务类解决子线程无法返回数据
- cookie和session
- 除非你是BAT,前端开发中最好少造轮子
- Windows环境下安装Redis
- FIFO管道通信(linux)
- .net/c#常用框架/中间件简介(不定时更新)
- cc2530启动流程---广播发送数据
- 简易画板-保存文件-刷新图库
- adb通过网络连接
- 正则表达式全部符号解释
- webpack 入门指南
- 内核探测工具systemtap简介
- jQuery.validate 中文API
- HashTable、HashMap、TreeMap梳理
- UIAlertController使用
- angular-ui-tree使用简介