leetcode-32. Longest Valid Parentheses

以下是别人比较好的解决方案,没有溢出问题,dp[i],表示已s[i]为结尾的合法括号的最大长度。

亮点:dp[i] += dp[i-dp[i]]

class Solution {
public:
   	int longestValidParentheses(string s){
		
		s = ')' + s; 
		int n = s.length();
		vector<int> dp(n ,0);
		
		int result = 0 ;
		for(int i = 1; i <n ; i++){
			if(s[i] == ')' ){
				if(	s[i-1-dp[i-1]] == '('){
					 dp[i] = dp[i-1] + 2;
				};
				dp[i] = dp[i] + dp[i-dp[i]];
				result = max(result , dp[i]);
			}
		}
		return result;
	}
};

  

猜你喜欢

转载自www.cnblogs.com/maggie94/p/10502064.html