zoukankan      html  css  js  c++  java
  • POJ 2752 Seek the Name, Seek the Fame(求所有既是前缀又是后缀的子串长度)

    题目链接:http://poj.org/problem?id=2752

    题意:给你一个字符串,求出所有前缀后缀(既是前缀又是后缀的子串)的长度

    思路:首先整个字符串肯定既是前缀又是后缀,为最大的前缀后缀。

    假设next[len] = k,也即:s[1,k] = s[len-k+1,len]此时s[1,k]是前缀后缀。

    处理完next[len]后跳转到next[k+1],用这种方法可以得到所有的前缀后缀。

    code:

     1 #include <cstdio>
     2 #include <cstring>
     3 const int MAXN = 400005;
     4 char str[MAXN];
     5 int next[MAXN];
     6 int ans[MAXN];
     7 void GetNext(int len)
     8 {
     9     int i = 0;
    10     int j = -1;
    11     next[0] = -1;
    12     while (i < len)
    13     {
    14         if (-1 == j || str[i] == str[j]) next[++i] = ++j;
    15         else j = next[j];
    16     }
    17 }
    18 
    19 int main()
    20 {
    21     while (scanf("%s", str) == 1)
    22     {
    23         int len = strlen(str);
    24         GetNext(len);
    25         int t = -1;
    26         ans[++t] = len;
    27         while (next[len] > 0)
    28         {
    29             ans[++t] = next[len];
    30             len = next[len];
    31         }
    32         for (int i = t; i > 0; --i) printf("%d ", ans[i]);
    33         printf("%d
    ", ans[0]);
    34     }
    35     return 0;
    36 }
  • 相关阅读:
    python Exception中的raise、assert
    python循环语句与其他编程语言不同之处
    【转】最大似然估计
    尝试发表代码
    奇异分解(SVD)
    Python学习笔记3-string
    梯度下降法
    前后端分离
    Trie树
    HashMap的工作原理以及代码实现,为什么要转换成红黑树?
  • 原文地址:https://www.cnblogs.com/ykzou/p/4468945.html
Copyright © 2011-2022 走看看