教訓(xùn)篇:負(fù)數(shù)不可以與unsigned比較

負(fù)數(shù)一定不可以與unsigned類型比較,先前看到過這種說(shuō)法,沒想到今天寫代碼的時(shí)候碰到了,在這里記錄一下。

class Solution {
public:
    void getNext(string s,int next[]){
        int k,j=0;
        next[0]=-1;
        k=next[j];
        while(j<s.length()-1){
            if(k==-1||s[k]==s[j]){
                j++;
                k++;
                next[j]=k;
            }else{
                k=next[k];
            }
        }
    }
    int strStr(string haystack, string needle) {
        if(needle.empty())
            return 0;
        int next[needle.length()];
        getNext(needle,next);
        int i=0,j=0;
        while(i<haystack.length()&&j<needle.length()){
            if(j==-1||haystack[i]==needle[j]){
                i++;
                j++;
            }else
                j=next[j];
        }
        if(j==needle.length())
            return i-j;
        else
            return -1;

    }
};

在實(shí)現(xiàn)KMP算法時(shí),在while(i<haystack.length()&&j<needle.length())判斷句中,因?yàn)閘ength()返回值是unsigned,而且j可能為負(fù)數(shù),所以出現(xiàn)了負(fù)數(shù)與unsigned比較的情況導(dǎo)致出錯(cuò),必須改為:

 int hlength=haystack.length(),nlength=needle.length();
 while(i<hlength&&j<needle.length)

以后一定要長(zhǎng)記性!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容