KMP + 求相等前后缀--- POJ Seek the Name, Seek the Fame

简介: Seek the Name, Seek the Fame  Problem's Link:  http://poj.org/problem?id=2752   Mean:  给你一个字符串,求这个字符串中有多少前缀是和后缀相等的, 按递增顺序输出这些前缀的长度。

Seek the Name, Seek the Fame 

Problem's Link:  http://poj.org/problem?id=2752


 

Mean: 

给你一个字符串,求这个字符串中有多少前缀是和后缀相等的, 按递增顺序输出这些前缀的长度。

analyse:

KMP之next数组的运用。

next[k]表示的是s[0....next[k]] 和s[k-next[k] .... k] 这段是相等的,即以k结尾的最长相等前后缀长度。

next[k-1]表示的是与s[0....k]具有最长后缀,且与s[0...k]具有最长前缀的位置。也就是在k位置失配后需要移到next[k-1]的位置。

这里特别说明一下,失配后移到next[k]还是next[k-1],取决于next数组的开始编号。如果从0开始编号,那就移到next[k-1];从1开始编号,就移到next[k]。

Time complexity: O(N)

 

Source code: 

/*
* this code is made by crazyacking
* Verdict: Accepted
* Submission Date: 2015-07-28-08.55
* Time: 0MS
* Memory: 137KB
*/
#include <queue>
#include <cstdio>
#include <set>
#include <string>
#include <stack>
#include <cmath>
#include <climits>
#include <map>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
#define  LL long long
#define  ULL unsigned long long
using namespace std;
const int MAXN = 400010;
int n;
char s [ MAXN ];
int Next [ MAXN ];
int ans [ MAXN ];
void getNext()
{
      Next [ 0 ] = 0;
      for( int i = 1 , k = 0; i <n; ++ i)
      {
            while(s [ i ] !=s [ k ] && k) k = Next [ k - 1 ];
            if(s [ i ] ==s [ k ]) ++ k;
            Next [ i ] = k;
      }
}
int main()
{
      ios_base :: sync_with_stdio( false);
      cin . tie( 0);
      while( ~ scanf( "%s" ,s))
      {
           n = strlen(s);
            getNext();
            int k =n - 1;
            int cnt = 0;
            while( Next [ k ])
            {
                  ans [ cnt ++ ] = Next [ k ];
                  k = Next [ k - 1 ];
            }
            ans [ cnt ++ ] =n;
            sort( ans , ans + cnt);
            for( int i = 0; i < cnt; ++ i)
            {
                  printf( i == cnt - 1 ? "%d \n " : "%d " , ans [ i ]);
            }
      }
      return 0;
}
/*

*/

 

目录
相关文章
|
7月前
|
算法
light oj 1255 - Substring Frequency (KMP)
输入两个字符串,计算二串在一串中出现的次数。 裸裸的KMP,参考刘汝佳《算法竞赛入门经典训练指南》 P212 或数据结构。
17 1
|
7月前
|
存储
华为机试HJ64:MP3光标位置
华为机试HJ64:MP3光标位置
|
9月前
模拟实现库函数strstr--查找子字符串
模拟实现库函数strstr--查找子字符串
|
12月前
|
C++
C++ 递归和非递归实现字符串反转 char *reverse(char *s)
C++ 递归和非递归实现字符串反转 char *reverse(char *s)
82 0
leetcode 28 找出字符串第一个匹配的下标(KMP实现strStr)
leetcode 28 找出字符串第一个匹配的下标(KMP实现strStr)
60 0
leetcode 28 找出字符串第一个匹配的下标(KMP实现strStr)
[路飞]_leetcode-1312-让字符串成为回文串的最少插入次数
leetcode-1312-让字符串成为回文串的最少插入次数
|
开发者 Python
seek( ) 和 tell( )|学习笔记
快速学习 seek( ) 和 tell( )
110 0
|
存储 算法 测试技术
Seek the Name, Seek the Fame(求名求名) (kmp) POJ-2752
题目:Seek the Name, Seek the Fame(求名求名)
|
C++ Windows Java
[LeetCode] Longest Absolute File Path 最长的绝对文件路径
Suppose we abstract our file system by a string in the following manner: The string "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.
1566 0