Click here to Skip to main content
15,888,097 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
leetcode32[^]
class Solution {
public:
  int longestValidParentheses(string s) {
    stack<int> q; //LIFO
    int start = 0;
    int ans = 0;
    for (int i = 0;i < s.length(); i++) {
      if(s[i] == '(') {
        q.push(i);
      } else {
        if (q.empty()) {
          start = i + 1;
        } else {
          int index = q.top(); q.pop();
          ans = max(ans, q.empty() ? i - start + 1 : i - q.top());    
if don't need
index
, why declare it?
        }
      }
    }
    return ans;
  }
};


What I have tried:

(why not choose the matched ‘(‘ but the previous one?)
Posted
Updated 24-Sep-20 23:45pm

You'd have to ask the original author, but it's either "I was going to do something with it, but didn't need to", "I'll remove it", or "It was useful for debugging".

The latter is the most likely: it makes it a lot easier to see what was the top item before it is removed when testing your code in the debugger.
I do it often: break down a complex line of code into lots of simpler ones each saving an intermediate result in a variable so they are easier to see. When it's all working, put it all back together and test it as a single item.

Sometimes you forget to remove the intermediate variables, is all.
 
Share this answer
 
Comments
Stefan_Lang 25-Sep-20 6:05am    
Agreed, I do the same. Except, when it's working, I leave it at the many simple steps. That way, when the next unfortunate guy gets to see that code he won't have to pick it apart again.
OriginalGriff 25-Sep-20 6:43am    
It affects my (mild) OCDness: I know the other variables will be optimised away, but ... it looks untidy! :laugh:
Quote:
(why not choose the matched ‘(‘ but the previous one?)

We can't help you because the code you provided is not a complete function.
As OG said only the author of that code can explain you what is what.
Quote:
why declare it?

If you can compile the code after commenting the line, then you don't need it.
 
Share this answer
 
v2
Comments
KarstenK 25-Sep-20 5:42am    
Bold words, if he comments out the line a q.pop() will be missing and the code wont run correctly. :-O
Best is to understand the code. A developer should understand every single line of its code.

You dont need that index so you may remove that command, BUT the code has the flaw that a q.pop() is on that line.

I guess that the function will need it :-O
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900