zoukankan      html  css  js  c++  java
  • Count the string

    题目大意:给你一个串求出来这个串所有的前缀串并且与前缀串相等的数量,比如:
    ababa 前缀串{"a", "ab", "aba", "abab", "ababa"};
    每个前缀串出现的次数{3, 2, 2, 1, 1},那么结果就是 9。
     
    分析:我们可以用dp[i],表示前i长度的串的结果,那么就可以得到下面的转移方程 dp[i] = dp[next[i]] + 1。
    代码如下。
    =============================================================================================
    #include<stdio.h>
    #include<string.h>
    
    const int MAXN = 1e6+7;
    const int oo = 1e9+7;
    const int mod = 10007;
    
    char s[MAXN];
    int next[MAXN], dp[MAXN];
    
    void GetNext(char s[], int N)
    {
        int i=0, j=-1;
        next[0] = -1;
    
        while(i < N)
        {
            if(j==-1 || s[i]==s[j])
                next[++i] = ++j;
            else
                j = next[j];
        }
    }
    
    int main()
    {
        int T, N, ans;
    
        scanf("%d", &T);
    
        while(T--)
        {
            scanf("%d%s", &N, s);
    
            GetNext(s, N);
    
            next[N+1] = -1;
            ans = dp[0] = 0;
    
            for(int i=1; i<=N; i++)
            {
                dp[i] = (dp[next[i]] + 1) % mod;
                ans = (ans+dp[i]) % mod;
            }
    
            printf("%d
    ", ans);
        }
    
        return 0;
    }
  • 相关阅读:
    [编程题-网易]小易的升级之路
    [腾讯编程题]微信红包
    [编程题]生成格雷码
    [编程题]二叉树-网易
    安装wepack
    css选择器
    宽和高
    配置环境变量
    offsetLeft在各浏览器的值
    容易忘记的css属性和动画属性
  • 原文地址:https://www.cnblogs.com/liuxin13/p/4732297.html
Copyright © 2011-2022 走看看