Reputation: 21
I found a code from someone to solve a code question, but I really don't understand this line
if(!(dp[i] = dp[i + 1] || str[i] != str[j]) && (e - s) <= (j - i))
, and what the array "dp" really do? What does dp[i] = dp[i+1]
mean? Isn't it assigning dp[i+1]
to dp[i]
??? Here is the code.
class Solution {
public:
string longestPalindrome(string str) {
const int n = str.size();
if(n < 2) return str;
int s = 0, e = 0;
int dp[n] = {0, };
for(int j = 0; j < n; ++j){
for(int i = 0; i < j; ++i){
if(!(dp[i] = dp[i + 1] || str[i] != str[j]) && (e - s) <= (j - i))
s = i, e = j;
}
}
return str.substr(s, e - s + 1);
}
};
Upvotes: 2
Views: 161
Reputation: 51815
What does dp[i] = dp[i+1] mean? Isn't it assigning dp[i+1] to dp[i]
Not exactly! As the ||
operator has higher precedence than the =
operator, the assignment is actually equivalent to this:
dp[i] = ( dp[i+1] || (str[i] != str[j]) );
But all expressions in C++
have a value as well as an effect. In the case of an assignment, like the one here, the value of the expression is the same as the value that is ultimately assigned (to the LHS). So, here, the value of the expression will be equal to the value of dp[i + 1]
logically ORed with the result of the str[i] != str[j]
comparison. If the i
and j
elements are not equal, then dp[i]
will be given the value of 1
; if they are the same, it will be given the value of dp[i+1]
.
The use of this expression inside a logical test condition achieves two things:
The second point is used to further evaluate the entire if
statement.
As this is the first expression to be evaluated, the code could be written more clearly (though less succinctly) as follows:
for(int i = 0; i < j; ++i){
dp[i] = dp[i + 1] || (str[i] != str[j]); // Do the assignment...
if((dp[i] == 0) && (e - s) <= (j - i)) // ... then test dp[i]
s = i, e = j;
}
Feel free to ask for further clarification and/or explanation.
Upvotes: 3