Can someone help me to understand below syntax... thanks in advance.
class Solution {
public:
int lengthOfLongestSubstring(string s) {
const int n = s.length();
int ans = 0; //set a var as 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;
}
};
wasn't sure what the syntax means
!seen[s[j]]
same as thisseen[s[j ]]=1
also don't know why i can be subtracted by j...
CodePudding user response:
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 lets 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 lets 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 2 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 i can be subtracted by j
This is because the value of j
is incremented by 1 inside the while loop.
CodePudding user response:
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