'Seeking helps in explanation of syntax for var[x[n]]

How does the below syntax work?

class Solution {

    public:

        int lengthOfLongestSubstring(string s) {
            const int n = s.length();
            int ans = 0; // Set a variable as the answer;
            for(int i = 0; i < n; ++i) {
                vector <int> seen(128);
                int j = i;
                while(j < n && !seen[s[j]]) <---- Here
                    seen[s[j++]] = 1;       <---- Here

                ans = max(ans, j - i);      <---- Here
            }
            return ans;
        }
};

What does the syntax !seen[s[j]] mean? And the same for seen[s[j++]]=1.

Also, why can i be subtracted by j?



Solution 1:[1]

Case 1

s[j]

The above means the element at index j of the string named s.

Case 2

seen[s[j]]

The above means the element at index s[j] of variable named seen.

Case 3

seen[s[j++]] = 1;

For the above you have to know about the post-increment operator. So let’s say we have:

int var = 0;
std::cout << var++ <<std::end; // This will print 0

The ++ in var++ means we are incrementing the value of var by 1, so that it now becomes 1, but var++ returns the old value of the variable var which is why we get 0 as the output.

Now let’s come back to:

seen[s[j++]]=1;

The above means the element at index s[j++] of the variable named seen. But note j++ will do two things: First it will increment j by 1 and second it will return the old value of j. So s[j++] essentially means the element at index j of the string named s meanwhile the value of j is also incremented by 1. Thus as a whole, you're assigning a value of 1 to the element at index s[j] of the variable named seen meanwhile also increment the value of j by one.

Why can i be subtracted by j?

This is because the value of j is incremented by 1 inside the while loop.

Solution 2:[2]

s[j] is the character at index j in the std::string s. seen[s[j]] is the element at index s[j] in the std::vector<int> seen.

If seen[s[j]] is 0, seen[s[j]] will return false, so !seen[s[j]] will return true. If seen[s[j]] is a nonzero value, seen[s[j]] will return true, so !seen[s[j]] will return false.

seen[s[j++]]=1; set the value of seen[s[j]] to 1, then increment j

ans = std::max(ans, j - i);, std::max(ans, j - i) will return the bigger value between ans, and j - i, then assign that value to ans

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Peter Mortensen
Solution 2 justANewb stands with Ukraine