mercredi 24 février 2021

C++, addition of unsigned offset how to solve?

I was trying to solve the following problem on leetcode:

https://leetcode.com/explore/interview/card/top-interview-questions-medium/103/array-and-strings/779/

Given a string s, find the length of the longest substring without repeating characters.

Example 1:

Input: s = "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3.

Constraints:

0 <= s.length <= 5 * 104 s consists of English letters, digits, symbols and spaces.

My suggested solution is:

class Solution {
public:
    const int MAX_LEN = 128;
    int lengthOfLongestSubstring(string s) {
        int max_len=0;
        int n=s.length();
        for (int i=0;i<n;++i)
        {
            int len=0;
            vector<int> his(MAX_LEN,0);
            for (int j=i;j<i+MAX_LEN, j<n;++j)
            {
                if (his[s[j]-'a']!=0)
                    break;
                ++his[s[j]-'a'];
                ++len;
                if (len>max_len) max_len=len;
            }
        }
        return max_len;
    }
};

but when I compile it on the website I get an error with the following input: " "

Line 1034: Char 34: runtime error: addition of unsigned offset to 0x615000003280 overflowed to 0x61500000317c (stl_vector.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1043:34

Aucun commentaire:

Enregistrer un commentaire