zoukankan      html  css  js  c++  java
  • SCU 4438 字符串哈希

     题意:一个敏感词w和一个文本p,在文本中不断地删除敏感词w,求最后的剩下的文本p。

    题解:求出敏感词的hash值,定p的每一个字符都是以第一个字符开始的一个句子,求出它们的hash值入栈,当某一段的hash值等于敏感词的hash值时,将这段字符出栈。

    #include <iostream>
    #include <cstring>
    #include <cstdio>
    
    using namespace std;
    
    #define maxn 5000006
    long long hash=100007;
    long long hash_w;
    long long hash_p[maxn];
    long long hash_pow[maxn];
    
    char p[maxn],w[maxn];
    char stack[maxn];
    int len;
    
    void init()
    {
        hash_pow[0]=1;
        for(int i=1;i<maxn;i++)
            hash_pow[i]=hash_pow[i-1]*hash;
    }
    
    bool check(int pos)
    {
        if(pos>=len && hash_p[pos]-hash_p[pos-len]*hash_pow[len]==hash_w)
            return true;
        return false;
    }
    
    int main()
    {
        init();
        while(~scanf("%s%s",w,p))
        {
            len=strlen(w);
            hash_w=0;
            for(int i=0;*(w+i);i++)
                hash_w=hash_w*hash+*(w+i);
            int top=0;
            for(int i=0;*(p+i);i++)
            {
                stack[top++]=*(p+i);
                hash_p[top]=hash_p[top-1]*hash+*(p+i);
                if(check(top)) top-=len;
            }
            for(int i=0;i<top;i++)
                printf("%c", stack[i]);
            printf("
    ");
        }
        return 0;
    }
    View Code
  • 相关阅读:
    leetcode-409
    leetcode-836
    leetcode-1160
    leetcode-面试题13
    leetcode-695
    go的一些小lib
    leetcode-300
    cookie
    php上传文件
    PHP 文件创建/写入
  • 原文地址:https://www.cnblogs.com/mgxj/p/5731412.html
Copyright © 2011-2022 走看看