Why do I have a run time error? C++ code

  • 0

    When the input is "au" I got a run time error.
    I don't think the problem comes from the logic of my code because I can run my program on my laptop just fine.
    I have not programmed much with C++. So I wonder whether there is some obvious problem(e.g. not have #include, not have namespace) in my code that causes leetcode to reject it?


    int lengthOfLongestSubstring(string s) {

    // the length of input string will be used many times so I called length.
    int length = s.length();
    if(length<=1) return length;
    int curr = 0; // curr points to each character in the input string.
    int table[256]; // table[256] will be used to record the charters appears so far.
    int max = 0; // record the length of longest substring.
    while(true) {
    	table[(int)s[curr]] = 1; // the current character is recorded as 1 which mean this character appears once.
    	int brave = curr+1;
    	// brave goes forward and stops at first character that appears twice.
    	while(brave<length && table[(int)s[brave]]==0){
    		table[(int)s[brave]] = 1; // record the appeared characters as 1.
    	for(int i=0; i<256; i++) table[i]=0; // clear the record of appearance of characters.
    	if(brave-curr>max) max = brave - curr; // (brave - curr) is the length of next non-repeated string.
    	if(brave==length) break;
    	// curr goto the next starting position getting ready to count next non-repeated string.
    	while(curr<length && s[curr]!=s[brave]) curr++;
    	curr = curr + 1;
    return max;


  • 1

    When you declare 'int table[256]', you must make sure that all elements are initialized to 0, otherwise your program won't function properly. This can be done by using

    int table[256] = {0};

    Otherwise, the values in table[] are undetermined, so you may get unexpected results, or even a run-time error.

  • 0

    Yes, it works indeed!

Log in to reply

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