用stack,并记录入栈的括号的位置
1 public class Solution { 2 class Node{ 3 char c; 4 int nub; 5 public Node(char c, int nub){ 6 this.c = c; 7 this.nub = nub; 8 } 9 } 10 11 public int longestValidParentheses(String s) { 12 // IMPORTANT: Please reset any member data you declared, as 13 // the same Solution instance will be reused for each test case. 14 15 char[] mychar = s.toCharArray(); 16 int result = 0; 17 int tmp = 0; 18 Stack<Node> mystack = new Stack<Node>(); 19 mystack.push(new Node(')', -1)); 20 21 for(int i=0; i < mychar.length; ++i) 22 { 23 if(mychar[i] == '(') 24 mystack.push(new Node('(',i)); 25 else 26 { 27 if(mystack.peek().c == '(') 28 { 29 mystack.pop(); 30 result = Math.max(result, i - mystack.peek().nub); 31 } 32 else 33 { 34 mystack.push(new Node(')',i)); 35 } 36 } 37 } 38 return result; 39 } 40 }