Home > front end >  Does this function vector<int> help(257, -1); creates 257 vectors with -1 elements each?
Does this function vector<int> help(257, -1); creates 257 vectors with -1 elements each?

Time:06-22

As I am referring this code from someone else.This is the solution of longest substring without repeating elements.So why are we using only (257,-1) over here?Can we use more than 257 over here or what?

 class Solution {
        public:
            int lengthOfLongestSubstring(string s) {
                vector<int> help(257, -1);
                int n = s.size(), ans = 0, curr = 0;
                for (int i = 0; i < n; i  ) {
                    if (help[s[i]] != -1) {
                        int temp = help[s[i]];
                        for (int x = curr; x <= temp; x  ) {
                            help[s[x]] = -1;
                        }
                        curr = temp 1;
                    }
                    help[s[i]] = i;
                    ans = max(ans, i-curr 1);
                }
                return ans;
            }
        };

CodePudding user response:

Does this function vector help(257, -1); creates 257 vectors with -1 elements each?

No, it creates 1 vector with 257 values that are all initialized to -1. See https://en.cppreference.com/w/cpp/container/vector/vector constructor #3. The first parameter is count of elements, the second is the initial value for each element.

So why are we using only (257,-1) over here?

I'm not entirely sure about this and you need to ask the author to be absolutely sure. It looks like each element of the vector stores the index of the last occurence of a character:

help[s[i]] = ...

s[i], which is used as index to help here, will return a char, which can take 256 different values. With this in mind, we can see that the largest possible index will be 255. That's where the size comes from (though 256 should suffice).

But it's not that easy: When input is restricted to ASCII-characters (0-127) this will work, however C allows char to be a signed type, i.e. on some systems char can be -128 to 127 instead of 0 to 255 which the author apparently expects. In this case, on some system, for certain inputs, you would try access a negative index on help, which is undefined behaviour. See also https://en.cppreference.com/w/cpp/language/types for more details on char.

  •  Tags:  
  • c
  • Related