[LeetCode] Longest Valid Parentheses

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.

 1 struct Node

 2 {

 3     char c;

 4     int index;

 5     Node(){}

 6     Node(char _c, int idx):c(_c), index(idx){}

 7 };

 8 

 9 class Solution {

10 public:

11     int longestValidParentheses(string s) {

12         // Start typing your C/C++ solution below

13         // DO NOT write int main() function

14         stack<Node> st;

15         st.push(Node(')', -1));

16         int ret = 0;

17         for(int i = 0; i < s.size(); i++)

18         {

19             char c = s[i];

20             if (c == '(')

21                 st.push(Node(c, i));

22             else

23             {

24                 Node node = st.top();

25                 if (node.c == '(')

26                 {

27                     st.pop();

28                     ret = max(ret, i - st.top().index);

29                 }

30                 else

31                     st.push(Node(c, i));                   

32             }

33         }

34         

35         return ret;

36     }

37 };

你可能感兴趣的:(LeetCode)