给定一个只包含
'('
和')'
的字符串,找出最长的包含有效括号的子串的长度。示例 1:
输入: "(()" 输出: 2 解释: 最长有效括号子串为"()"
示例 2:
输入: ")()())" 输出: 4 解释: 最长有效括号子串为"()()"
用栈来做。DP做法可能以后更新。先附上栈的做法。
创立一个栈,遍历字符串,左括号入栈,遇到右括号,如果当前栈为空,则用start记录下一个位置。
如果栈不为空,则将栈顶元素弹出(因为栈里存的都是左括号),如果弹出栈顶元素后栈为空,则更新
i-start+1的的较大值,如果不为空,更新i-栈顶元素中的最大值。class Solution { public: int longestValidParentheses(string s) { int res = 0, start = 0; stack<int> m; for (int i = 0; i < s.size(); ++i) { if (s[i] == '(') m.push(i); else if (s[i] == ')') { if (m.empty()) start = i + 1; //start记录有效串的起始位置 else { m.pop(); if (m.empty()) { res = max(res, i - start + 1); } else { int a = m.top(); res= max(res, i - m.top()); } } } } return res; } };