zoukankan      html  css  js  c++  java
  • POJ 2752 Seek the Name, Seek the Fame KMP

    题意:给你一个字符串,问你有多少组前缀等于后缀

    解题思路:用到next数组的性质,next数组实际上求的就是最大前缀后缀,把所有情况求出只需要递归即可。

    解题代码:

     1 // File Name: getnext.cpp
     2 // Author: darkdream
     3 // Created Time: 2014年09月09日 星期二 22时35分02秒
     4 
     5 #include<vector>
     6 #include<list>
     7 #include<map>
     8 #include<set>
     9 #include<deque>
    10 #include<stack>
    11 #include<bitset>
    12 #include<algorithm>
    13 #include<functional>
    14 #include<numeric>
    15 #include<utility>
    16 #include<sstream>
    17 #include<iostream>
    18 #include<iomanip>
    19 #include<cstdio>
    20 #include<cmath>
    21 #include<cstdlib>
    22 #include<cstring>
    23 #include<ctime>
    24 #define LL long long
    25 
    26 using namespace std;
    27 char str[1000005];
    28 char str1[1000005];
    29 int next[1000005];
    30 void getnext()
    31 {
    32    int len = strlen(str1);
    33    next[0] = -1; 
    34    int k = -1;
    35    int j = 0 ; 
    36    while(j <= len - 1)
    37    {
    38       if(k == -1 || str1[j] == str1[k])
    39       {
    40          ++j; 
    41          ++k;
    42              next[j] = k ;
    43       }
    44       else {
    45          k = next[k];
    46       }
    47    }
    48 }
    49 int kmp()
    50 {
    51   int sum = 0 ; 
    52   int len = strlen(str);
    53   int len1 = strlen(str1);
    54   int i = 0 ; 
    55   int j = 0 ;
    56   getnext();
    57   while(i < len )
    58   {
    59      if(j ==  -1 || str[i] == str1[j])
    60      {
    61         i ++ ;
    62         j ++ ;
    63      }else{
    64        j = next[j];
    65      }
    66      if(j == len1 )
    67      {
    68         sum ++ ; 
    69      }
    70   }
    71   printf("%d
    ",sum);
    72 }
    73 int main(){
    74     int t; 
    75     scanf("%d",&t);
    76     while(t--)
    77     { 
    78         scanf("%s",str1);
    79         scanf("%s",str);
    80         kmp(); 
    81     }
    82     return 0;
    83 }
    View Code
    没有梦想,何谈远方
  • 相关阅读:
    java 变量的定义 类型转换 基本的数据类型
    Java中的String,StringBuilder,StringBuffer三者的区别?
    Linux配置 ElasticSearch
    Linux 配置 SVN and ideal 配置SVN的客户端 ?
    mysql5.7多实例安装
    MySQL高可用架构之MySQL5.7组复制MGR
    二进制安装MySQL5.6 MySQL5.7
    MySQL主从复制之半同步模式
    MySQL主从复制之异步模式
    基于GTID模式MySQL主从复制
  • 原文地址:https://www.cnblogs.com/zyue/p/3963870.html
Copyright © 2011-2022 走看看