# My simple 8ms C++ code

• ``````class Solution {
public:
int longestValidParentheses(string s) {
stack<int> stk;
stk.push(-1);
int maxL=0;
for(int i=0;i<s.size();i++)
{
int t=stk.top();
if(t!=-1&&s[i]==')'&&s[t]=='(')
{
stk.pop();
maxL=max(maxL,i-stk.top());
}
else
stk.push(i);
}
return maxL;
}
};``````

• nice solution. work like a charm.

• cleverest solution of all!

• This post is deleted!

• ``````//can you help me with my solution?

class Solution
{
public:
int longestValidParentheses(string s){
stack <int> ss;
int len=s.size();
int result=0,accu=0;
for (int i=0;i<len;i++){
if (s[ss.top()]=='(' && !ss.empty() && s[i]==')' ){
ss.pop();
if (ss.empty()){
result= i+1;
}
else{
result= max(i-ss.top(),result);
}
}
else{
ss.push(i);
}
}

return result;
}
};``````

• 6666666666666666

• Thanks for your excellent code! I did a small change, 6ms
'''
class Solution {
public:
int longestValidParentheses(string s) {
stack<int> stk;
stk.push(-1);
stk.push(0);
int maxL=0;
for(int i=1;i<s.size();i++)
{
int t=stk.top();

``````        if(s[i]==')' && s[t]=='(')
{
stk.pop();
maxL=max(maxL,i-stk.top());
}
else
stk.push(i);
}
return maxL;
}
``````

};
'''

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.