# 32. Longest Valid Parentheses

----------------------------------------------------------------------------

Mean:

analyse:

1. 栈顶元素为'('，正好匹配，将栈顶元素出栈;
2. 栈顶元素为')'或栈为空，将当前符号和下标入栈.

trick：注意'(()'这种情况，需要特判，即backVal的值为len.

Time complexity: O(N)

view code

/**
* -----------------------------------------------------------------
* -----------------------------------------------------------------
*       Author: crazyacking
*       Date  : 2016-03-01-20.35
*/
#include <queue>
#include <cstdio>
#include <set>
#include <string>
#include <stack>
#include <cmath>
#include <climits>
#include <map>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;
typedef long long( LL);
typedef unsigned long long( ULL);
const double eps( 1e-8);

class Solution
{
public :
int longestValidParentheses( string s)
{
int len =s . length();
stack < pair < char , int >> sta;
for( int i = 0; i < len; ++ i)
{
if(s [ i ] == '(')
sta . push( make_pair( '(' , i));
else
{
if( ! sta . empty())
{
pair < char , int > t = sta . top();
if( t . first == '(')
sta . pop();
else
sta . push( make_pair( ')' , i));
}
else
sta . push( make_pair( ')' , i));
}
}

int ans = 0 , frontVal = len , backVal;
if( ! sta . empty() && sta . top (). second != len - 1)
backVal = len;
else
backVal = len - 1;
while( ! sta . empty())
{
pair < char , int > t = sta . top();
sta . pop();
frontVal = t . second;
ans = max( ans , backVal - frontVal - 1);
backVal = frontVal;
}
ans = max( ans , frontVal - 0);
return ans;
}
};

int main()
{
Solution solution;
string s;
while( cin >>s)
{
cout << solution . longestValidParentheses(s) << endl;
}
return 0;
}
/*

*/

|
10月前
Leetcode 516. Longest Palindromic Subsequence

38 0
|
3月前
|

LeetCode 题目 65：有效数字（Valid Number）【python】
LeetCode 题目 65：有效数字（Valid Number）【python】
41 5
|
10月前
|
Java
Leetcode 3. Longest Substring Without Repeating Characters

41 3
LeetCode Contest 178-1368. 使网格图至少有一条有效路径的最小代价 Minimum Cost to Make at Least One Valid Path in a Grid
LeetCode Contest 178-1368. 使网格图至少有一条有效路径的最小代价 Minimum Cost to Make at Least One Valid Path in a Grid
102 0
LeetCode 424. Longest Repeating Character Replacem

97 0
LeetCode 409. Longest Palindrome

67 0
LeetCode 395. Longest Substring with At Least K

76 0
|
Windows
LeetCode 388. Longest Absolute File Path

70 0
LeetCode 367. Valid Perfect Square

89 0
|

LeetCode 329. Longest Increasing Path in a Matrix

60 0