UVa 455 Periodic Strings

来源:互联网 发布:java搜索引擎lucene 编辑:程序博客网 时间:2024/06/09 16:13

本题是在ACM比赛中经常出现的一类题目,找出最小子串的问题,可用多种方法求解,在这里列举几种

一、直接暴力枚举法

#include <iostream>  #include <cstdlib>  #include <cstring>  #include <cstdio>  using namespace std;  char str[104];  int main()  {     int n;     while (~scanf("%d",&n))     while (n --) {         scanf("%s",str);         int len = strlen(str);          for (int k,i = 1 ; i <= len ; ++ i) //逐一枚举子串长度,直到能满足条件            if (len%i == 0) { //要能被字符串长度整除的                for (k = i ; k < len ; ++ k)                     if (str[k] != str[k%i])                         break;                 if (k == len) {                     printf("%d\n",i);                     break;                 }          }          if (n) printf("\n");      }      return 0;  } 

二、KMP算法求解

这里简单介绍一下KMP算法,一般情况下利用遍历搜索的方式匹配子串,但在大数据量的情况下效率比较低,由此较为高效的算法KMP算法就这样形成了。KMP算法的难点就在于next数组的规律,只要搞清楚next数组的变化情况还是比较好理解的。

KMP算法的代码:(函数)

这里写代码片
1 0
原创粉丝点击