Description:
Given a string containing just the characters ’(’ and ’)’, find the length of the longest valid (wellformed) parentheses substring.
For ”(()”, the longest valid parentheses substring is ”()”, which has length = 2.
Another example is ”)()())”, where the longest valid parentheses substring is ”()()”, which has
length = 4
分析:
使用栈
代码:
#include <iostream>
#include <string>
#include <stack>
#include <algorithm>
using namespace std;
string LongestValidParentheses(string str)
{
int len = str.size();
string result = "";
stack<char> sk;
string leftBracket = "([{";
string rightBracket = ")]}";
string temp = "";
for (int i = 0; i < len; i++)
{
if (leftBracket.find(str[i]) != string::npos)
sk.push(str[i]);
if (rightBracket.find(str[i]) != string::npos)
{
if (!sk.empty())
{
if (sk.top() == leftBracket[rightBracket.find(str[i])])
{
temp = temp + sk.top() + str[i]; //record continuous valid parentheses
}
else
temp = "";
sk.pop();
if (result.size() < temp.size())
result = temp;
}
}
}
return result;
}
int main()
{
string str = "(()";
string str2 = ")()())";
string str3 = "{}([])";
string str4 = "{()][][]}";
cout << LongestValidParentheses(str) << endl;
cout << LongestValidParentheses(str2) << endl;
cout << LongestValidParentheses(str3) << endl;
cout << LongestValidParentheses(str4) << endl;
system("pause");
return 0;
}
测试: