12ms and O(n) time C++ code. Easy to understand!


  • -3
    B

    class Solution {
    public:
    int longestValidParentheses(string s) {

    if (s.empty()) return 0;
    stack<int> ass;
    int currentLen = 0, maxLen = 0;
    for (int i = 0; i < (int)s.size(); i++)
    {
    	if (s[i] == '(' || ass.empty() || s[ass.top()] == ')')
    		ass.push(i);
    	else
    	{
    		ass.pop();
    		if (ass.empty())
    			currentLen = i + 1;
    		else
    			currentLen = i - ass.top();
    		if (currentLen > maxLen)
    			maxLen = currentLen;
    	}
    }
    return maxLen;
    }
    

    };


Log in to reply
 

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