题目:斤斤计较得小Z(蓝桥OJ 2047)

问题描述: 


题解:

        做法一(kmp模板):

#include <bits/stdc++.h>
using namespace std;

const int N = 1e6 + 9;
char s[N], p[N];
int nex[N];

int main()
{
  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);

  // p: 子串  s:文本串
  cin >> p + 1;int m = strlen(p + 1);
  cin >> s + 1;int n = strlen(s + 1);

  nex[0] = nex[1] = 0;
  for(int i = 2,j = 0; i <= m; i++)
  {
    while(j && p[i] != p[j + 1])j = nex[j];
    if(p[i] == p[j + 1])j++;
    nex[i] = j;
  }

  int ans = 0;
  for(int i = 1,j = 0; i <= n; i++)
  {
    while(j && s[i] != p[j + 1])j = nex[j];
    if(s[i] == p[j + 1])j++;
    if(j == m)ans++;
  }
  cout << ans << '\n';
  return 0;
}

        做法二 (字符串hash)  :

#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 9;
char s[N], p[N];
using ull = unsigned long long;
const ull base = 131;
ull h1[N], h2[N], b[N];  // h1:子串哈希  h2:文本串哈希  b[N]:b的i次方 

ull getHash(ull h[], int l, int r)  // 获取新的独一的以l开头的r结尾的r的哈希值 
{
	return h[r] - h[l - 1] * b[r - l + 1]; 
}

int main()
{
  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);

  // p: 子串  s:文本串
  cin >> p + 1;int m = strlen(p + 1);
  cin >> s + 1;int n = strlen(s + 1);
  b[0] = 1;
  for(int i = 1; i <= n; i++)  // 初始化 
  {
	b[i] = b[i - 1] * base;
	h1[i] = h1[i - 1] * base + (int)p[i];  // (int)p[i]:第i位的ascii值 
  	h2[i] = h2[i - 1] * base + (int)s[i];
  }
  
  int ans = 0;
  for(int i = 1; i + m - 1 <= n; i++)  // 枚举文本串的子串位置,i+m-1表示以i开头的子串的末尾,子串末尾上限到文本串末尾 
  {
  	if(getHash(h1, 1, m) == getHash(h2, i, i+m-1))ans++;
  }

  cout << ans << '\n';
  return 0;
}

知识点:kmp模板,字符串hash

相关推荐

最近更新

  1. TCP协议是安全的吗?

    2024-04-12 23:48:02       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-12 23:48:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-12 23:48:02       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-12 23:48:02       20 阅读

热门阅读

  1. Object.assign详解

    2024-04-12 23:48:02       13 阅读
  2. c++成绩排名

    2024-04-12 23:48:02       15 阅读
  3. js中如何进行隐式类型转换

    2024-04-12 23:48:02       14 阅读
  4. 【5】c++多线程技术之线程间通信

    2024-04-12 23:48:02       14 阅读
  5. 个人博客项目笔记_02

    2024-04-12 23:48:02       14 阅读
  6. 【C语言】- C语言字符串函数详解

    2024-04-12 23:48:02       13 阅读
  7. 飞机降落(蓝桥杯)

    2024-04-12 23:48:02       20 阅读