Title:
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.
思路:题目中需要匹配的是字串。对于这样的问题,通常思路是使用stack
struct Node { char c; int index; Node(){} Node(char _c, int idx):c(_c), index(idx){} }; class Solution { public: int longestValidParentheses(string s) { // Start typing your C/C++ solution below // DO NOT write int main() function stack<Node> st; st.push(Node(')', -1)); int ret = 0; for(int i = 0; i < s.size(); i++) { char c = s[i]; if (c == '(') st.push(Node(c, i)); else { Node node = st.top(); if (node.c == '(') { st.pop(); ret = max(ret, i - st.top().index); } else st.push(Node(c, i)); } } return ret; } };