Weird C++ runtime error


  • 0
    W

    I met with a so weird C++ runtime error
    At first. I try this code:

    class Solution {
    public:
        int strStr(string haystack, string needle) {
            int i;
            for(i=0;i<haystack.size()-needle.size()+1;i++){
                if(needle==haystack.substr(i,needle.size()))
                    return i;
            }
            return -1;
        }
    };
    

    And when it come to case:
    "abb"
    "abaaa"
    There is a runtime error.

    But when I try this code:

    class Solution {
    public:
        int strStr(string haystack, string needle) {
            int i,len;
            len = haystack.size()-needle.size()+1;
            for(i=0;i<len;i++){
                if(needle==haystack.substr(i,needle.size()))
                    return i;
            }
            return -1;
        }
    };
    

    The code is accepted.
    I dk why?? I just replace 'haystack.size()-needle.size()+1' with 'len' in 'for' and there is no runtime error...
    Am I misunderstanding something about 'for'?


Log in to reply
 

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