社区讨论

关于substr()函数与字符串哈希

学术版参与者 4已保存回复 4

讨论操作

快速查看讨论及其快照的属性,并进行相关操作。

当前回复
4 条
当前快照
1 份
快照标识符
@lobzylpm
此快照首次捕获于
2023/10/30 05:42
2 年前
此快照最后确认于
2023/11/04 10:58
2 年前
查看原帖
TLE写法
CPP
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>

using namespace std;

typedef unsigned long long ULL;

int n;
string s1;

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cin >> s1 >> n;
    s1 = " " + s1;
    while(n --)
    {
        int l1, r1, l2, r2;
        cin >> l1 >> r1 >> l2 >> r2;
        if(s1.substr(l1, r1 - l1 + 1) == s1.substr(l2, r2 - l2 + 1)) cout << "Yes" << endl;
        else cout << "No" << endl;
    }

    return 0;
}
AC写法
CPP
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>

using namespace std;

typedef unsigned long long ULL;

const int N = 1e6 + 10, P = 13331;

int hx[N], p[N];
int n;
char str[N];

inline int H(int l, int r)
{
    return hx[r] - hx[l - 1] * p[r - l + 1];
}

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cin >> str + 1 >> n;
    int len = strlen(str + 1);
    p[0] = 1;
    for(int i = 1; i <= len; i ++)
    {
        hx[i] = hx[i - 1] * P + (str[i] - 'a' + 1);
        p[i] = p[i - 1] * P;
    }
    while(n --)
    {
        int l1, r1, l2, r2;
        cin >> l1 >> r1 >> l2 >> r2;
        if(H(l1, r1) == H(l2, r2)) cout << "Yes" << endl;
        else cout << "No" << endl;
    }

    return 0;
}
substr() 函数的时间复杂度是多少,直接以substr() 来判等与字符串哈希来判等的时间能差多少? 是substr()常数大嘛?能差多少倍呢qwq

回复

4 条回复,欢迎继续交流。

正在加载回复...