top1编程
← 返回题目
题解

【模板】字符串哈希

1 条题解

  • 0
    @ 2026-10-21 1:03:08

    1. 解题思路

    将字符串按字典序排序,相同字符串相邻,用unique统计不同字符串数量。

    2. 坑点和注意事项

    N≤10000,串长≤1500,区分大小写;直接比较字符串避免哈希碰撞,比较开销最多为串长L。

    3. 复杂度

    • 时间复杂度:O(NL log N)。
    • 空间复杂度:O(NL)。
    /*
    思路:将字符串按字典序排序,相同字符串相邻,用unique统计不同字符串数量。
    关键规则与坑点:N≤10000,串长≤1500,区分大小写;直接比较字符串避免哈希碰撞,比较开销最多为串长L。
    时间复杂度:O(NL log N)。空间复杂度:O(NL)。
    */
    #include <bits/stdc++.h>
    using namespace std;
    int main()
    {
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
        int n;
        cin >> n;
        static string a[10000];
        for (int i = 0; i < n; i++)
            cin >> a[i];
        sort(a, a + n);
        cout << unique(a, a + n) - a << '\n';
    }
    
    • 1