The Problem:
Given a string containing just the characters ‘(‘ and ‘)’, find the length of the longest valid (well formed) parentheses sub-strings.
#include <iostream>
#include <string>
#include <stack>
using namespace std;
int longest_valid_parentheses(string const& s) {
int count = 0, max_count = 0;
stack<char> stk;
for(auto c : s) {
if(c == '(')
stk.push(c);
else {
if( stk.empty() ) //|| stk.top() != '(')
count = 0;
else {
count += 2;
stk.pop();
}
}
max_count = count > max_count ? count : max_count;
}
return max_count;
}
You can test the above code using the following test cases @ http://www.cpp.sh/.
int main()
{
string test1("(()");
string test2("(()()(");
string test3(")()()))(((())))");
cout << "there are " << longest_valid_parentheses(test1) << " valid parentheses in " << test1 << endl;
cout << "there are " << longest_valid_parentheses(test2) << " valid parentheses in " << test2 << endl;
cout << "there are " << longest_valid_parentheses(test3) << " valid parentheses in " << test3 << endl;
return 0;
}
The output would look like as the follows:
there are 2 valid parentheses in (() there are 4 valid parentheses in (()()( there are 8 valid parentheses in )()()))(((())))