当前位置:网站首页>【 size_t is unsigned integer (1 > 10) - > 1.

【 size_t is unsigned integer (1 > 10) - > 1.

2022-08-09 09:58:00 A rebellious above the waist

c++中string 的size() 函数返回的类型是size_t
是一个无符号整数
size_t介绍
!!!!!!!!!!
所以就会出现-1 > 10 的情况
因为-1 Look at the unsigned case 就是 ff ff ff ff(补码形式)
今天写kmp遇到的一个问题
还以为是我kmp都写不出来了.
This problem can only blame myself for being too careless.
Please attach the correct code

void nextT(string &t, vector<int> &next,int n)
{
    
    int j = 0, k = -1;
    next[0] = -1;
    while(j < n-1) {
    
        if(k == -1 || t[j] == t[k]) {
    
            next[++j] = ++k;
        } else {
    
            k = next[k];
        }
    }
}
int KMP(string &s, string &t)
{
    
    int m = s.size();
    int n = t.size();
    int i = 0, j = 0;
    vector<int> next(n);
    nextT(t,next,n);

    while(i < m && j < n) {
    
        if(j == -1 || s[i] == t[j]) {
    
            ++i;
            ++j;
        } else {
    
            j = next[j];
        }
    }
    if(j == n)
        return i - j;
    return -1;
}

int strStr(string haystack, string needle)
{
    
    return KMP(haystack,needle);
}
原网站

版权声明
本文为[A rebellious above the waist]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/221/202208090945032038.html