题目:斤斤计较得小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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值