leetcode 28 Implement strStr() 练习使用后缀数组

  • 这次主要是利用一道字符串匹配的简单题,自己实现一遍后缀数组

实现

class Solution {
public:
    vector<int> sa, rank, tmp;
    void getSa(const string& s){
        int n = s.length();
        for (int i = 0; i < n; i++){
            rank.push_back(s[i]);
            sa.push_back(i);
            tmp.push_back(0);
        }
        rank.push_back(-1);
        tmp.push_back(0);
        sa.push_back(n);
        for (int k = 1; k <= n; k *= 2){
            auto cmp = [&](int x, int y){
                if (rank[x] != rank[y])
                    return rank[x] < rank[y];
                int t1 = x + k <= n ? rank[x + k] : -1;
                int t2 = y + k <= n ? rank[y + k] : -1;
                return t1 < t2;
            };
            sort(sa.begin(), sa.end(), cmp);
            tmp[sa[0]] = 0;
            for (int i = 1; i <= n; i++){
                if (cmp(sa[i-1], sa[i])){
                    tmp[sa[i]] = tmp[sa[i-1]] + 1;
                }
                else {
                    tmp[sa[i]] = tmp[sa[i-1]];
                }
            }
            for (int i = 0; i <= n; i++)
                rank[i] = tmp[i];
        }
    }
    
    int strStr(string haystack, string needle) {
        getSa(haystack);
        int l = 0, r = haystack.length();
        int low = -1, high = -1;
        while (l <= r){
            int mid = (l + r) >> 1;
            int f = haystack.compare(sa[mid], needle.length(), needle);
            if (f < 0){
                l = mid + 1;
            }
            else if (f == 0){
                r = mid - 1;
                low = mid;
            }
            else {
                r = mid - 1;
            }
        }
        l = 0, r = haystack.length();
        while (l <= r){
            int mid = (l + r) >> 1;
            int f = haystack.compare(sa[mid], needle.length(), needle);
            if (f < 0){
                l = mid + 1;
            }
            else if (f == 0){
                l = mid + 1;
                high = mid;
            }
            else {
                r = mid - 1;
            }
        }
        int ans = INT_MAX;
        for (int i = max(low, 0); i <= high; i++){
            ans = min(sa[i], ans);
        }
        if (ans != INT_MAX && haystack.compare(ans, needle.length(), needle) == 0)
            return ans;
        else
            return -1;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值