Lint Code 1365. Minimum Cycle Section

This problem can be seen as a simplified version of POJ 1961's minimal loop section. The reference solution of the two pointers given in the advertisement post of a cram school is simply wrong.

Inspired by POJ 1961, it can be observed that if the array is all composed of cyclic sections, the longest matching prefix of the string without the last character is the smallest cyclic section. And "the longest matching prefix of the last character" is pattern[length -1] in KPM. So we only need to find the mismatch function according to the standard KMP algorithm.

    int minimumCycleSection(vector<int> &a) {
        size_t len = a.size();
        if(len <= 1) return len;
        int pattern[len];
        memset(pattern, 0, len * 4);
        pattern[0] = -1;
        for(size_t i = 1; i < len; i++){
            int j = pattern[i-1]+1;
            while(a[i] != a[j] && j > 0){
                j = pattern[j-1] + 1;
            }
            pattern[i] = a[i] == a[j] ? j : -1;
        }
        return len - pattern [len- 1 ] - 1 ;
    }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325155279&siteId=291194637
Recommended