Bootstrap

迟到的题解,力扣周赛第四题100207. 找出数组中的美丽下标 II

class Solution {
public:
void computeLPSArray(const std::string& pattern, std::vector<int>& lps) {
    int length = 0;
    int i = 1;
    lps[0] = 0;

    while (i < pattern.length()) {
        if (pattern[i] == pattern[length]) {
            length++;
            lps[i] = length;
            i++;
        } else {
            if (length != 0) {
                length = lps[length - 1];
            } else {
                lps[i] = 0;
                i++;
            }
        }
    }
}
int findAndRecordKMP(std::string& source, std::string& target, int positions[], int& count) {
    int sourceLen = source.length();
    int targetLen = target.length();

    // Create and compute LPS array
    std::vector<int> lps(targetLen, 0);
    computeLPSArray(target, lps);

    int i = 0;  // Index for source
    int j = 0;  // Index for target

    while (i < sourceLen) {
        if (target[j] == source[i]) {
            j++;
            i++;
        }
        if (j == targetLen) {
            positions[count++] = i - j;
            j = lps[j - 1];
        } else if (i < sourceLen && target[j] != source[i]) {
            if (j != 0) {
                j = lps[j - 1];
            } else {
                i++;
            }
        }
    }
    return count;
}
    bool st[510000];
    int a_index[510000]; // Assuming a maximum size for the array
    int b_index[510000]; // Assuming a maximum size for the array
    vector<int> beautifulIndices(string s, string a, string b, int k) 
    {
        //memset(st, 0, sizeof(st));
        int count_a = 0, count_b = 0;

       findAndRecordKMP(s, a, a_index, count_a);
       findAndRecordKMP(s, b, b_index, count_b);

        sort(b_index, b_index + count_b);

        vector<int> res;

        for (int i = 0; i < count_a; i++) {
            int _i_index = a_index[i];
            if (st[_i_index]) continue;

            int zhen_j = _i_index - k;
            int fu_j = k + _i_index;

            auto it_lower = lower_bound(b_index, b_index + count_b, zhen_j);
            if (it_lower != b_index + count_b) {
                if ((abs(*it_lower - _i_index) <= k)) {
                    res.push_back(_i_index);
                    st[_i_index] = true;
                }
            }
            
            auto it_upper = upper_bound(b_index, b_index + count_b, fu_j);
            if (st[_i_index]) continue;
            if (it_upper != b_index + count_b) {
                if ((abs(*it_upper - _i_index) <= k)) {
                    res.push_back(_i_index);
                    st[_i_index] = true;
                }
            }
        }
        return res;
    }
};

就是在第二题的基础上预处理a数组和b数组的用的find改成kmp算法进行预处理下标

;