Why a small change make it have a runtime error ?

  • 0

    for test case: haystack = "aaa", needle = "aaaaa".
    It works fine so far, but if I change "i < v" to "i < haystack.size() - size_s + 1", it will have a runtime error, why it make a difference?

    class Solution {
        int strStr(string haystack, string needle) {
            if (needle.empty()) return 0;
            int size_s = needle.size();
            int v = haystack.size() - size_s + 1;
            for (int i = 0; i < v; ++i) {
                if (haystack[i] == needle[0]) {
                    if (needle == haystack.substr(i, size_s))
                        return i;
            return -1;

  • 0

    It's because haystack.size() is an unsigned int, when you do "i<haystack.size()-size_s+1", you were mixing unsigned int and int together, and you were trying to compare them, which could cause strange behavior.
    The quickest fix is to write "for(int i=0;i<(int)(haystack.size()-size_s+1);++i" , or just as what you did to get AC.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.