***LintCode 1365. Minimum Cycle Section | kmp 据说是头条的笔试题第一题

https://www.lintcode.com/problem/minimum-cycle-section/description

这题据说是头条笔试第一题,看了下 对非ACMer而言,或者我这种比较菜 而且忘得差不多的 真是有点难啊......

参考了这里 https://www.jiuzhang.com/solution/minimum-cycle-section/

复习一下kmp:

next[i] = v,表示如果跟pat[i]不匹配,那么就从pat[v]重新开始尝试匹配

想下循环节的特点:

index: 0 1 2 3 4 5 6 7

数组: 1 2 1 2 1 2 3 1

next: -1 0 1 2 3 4 0 1

可以看出来 循环节长度+next[end] - 1 = end -1

可以加上上面的序列是121212验证一下上面吗的式子

end 的index是6

class Solution {
public:
    /**
     * @param array: an integer array
     * @return: the length of the minimum cycle section
     */
    int minimumCycleSection(vector<int> &array) {
        vector<int> next(array.size()+1, 0);
        int i = 0, j = -1;
        next[0] = -1;
        while (i < array.size()) {
            if (j == -1 || array[i] == array[j]) {
                i++;
                j++;
                next[i] = j;
            } else {
                j = next[j];
            }
        }
        
        return i - next[i];
        
        // for (int i = 0; i < array.size(); i++) 
    }
};




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值