My simple 8ms C++ code


  • 67
    P
    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;
        }
    };

  • 0
    R

    nice solution. work like a charm.


  • 1
    A

    cleverest solution of all!


  • 0
    J
    This post is deleted!

  • 0
    J
    //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;
        	}
        };

  • 0
    I

    6666666666666666


  • 0
    W

    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;
    }
    

    };
    '''


Log in to reply
 

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