原题地址:
https://leetcode-cn.com/problems/longest-valid-parentheses/description/
题目描述:
给定一个只包含 '('
和 ')'
的字符串,找出最长的包含有效括号的子串的长度。
示例 1:
输入: "(()"
输出: 2
解释: 最长有效括号子串为 "()"
示例 2:
输入: ")()())
" 输出: 4 解释: 最长有效括号子串为"()()"
解题方法:
class Solution { public: int longestValidParentheses(string s) { stack<int> stk; int count = 0; int max = 0; int m = 0; int n = s.size(); int* a = new int[n]; for(int i = 0; i < n; i ++) a[i] = 0; for(int i = 0; i < n; i ++){ if(s[i] == '(') stk.push(m++); else if(!stk.empty()){ int tmp = stk.top(); stk.pop(); a[tmp] = 1; } else m ++; } for(int i = 0; i < s.size(); i ++) if(a[i] == 1) count += 2; else{ if(count > max) max = count; count = 0; } return max; } };