题目:
Given a string containing just the characters
‘(‘and‘)‘, find the length of the longest valid (well-formed) 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.
意思是就是找出最长的括号匹配的长度。
这道题也有很多报告,大概看了一点,我看到的多是DP和用栈来做标记,都有用到O(N)的空间复杂度。其实O(N)的空间复杂度是不必要的,提出一个O(N)时间,O(1)空间的解法。
主要思路是正序逆序各遍历一次【正序需要遍历,逆序最差需要遍历】。
public class Solution {
public int longestValidParentheses(String s) {
int left = 0 , len = 0 , tmpl = 0 , pos = -1;
for( int i = 0; i != s.length(); i++ ){
if( s.charAt(i) == '(' ){
left ++; tmpl ++;
}else{
left --;
if( left == -1 ){
if( tmpl > len ){
len = tmpl;
}
left = 0; tmpl = 0;
pos = i;
}else{
tmpl ++;
}
}
}
if( left > 0 ){
left = 0; tmpl = 0;
for( int i = s.length() - 1 ; i != pos; i-- ){
if( s.charAt(i) == ')' ){
left ++; tmpl ++;
}else{
left --;
if( left == -1 ){
if( tmpl > len ){
len = tmpl;
}
left = 0; tmpl = 0;
}else{
tmpl ++;
}
}
}
}
if( left == 0 ){
if( tmpl > len ) len = tmpl;
}
return len;
}
}
LeetCode: Longest Valid Parentheses O(n)时间 O(1)空间
原文:http://blog.csdn.net/taoxin52/article/details/41555521