LeetCode: Longest Valid Parentheses
用dfs large超时,看了网上答案用stack,其实一开始也想到了,只是没预料到stack比dfs更优越
1 class Solution { 2 public: 3 struct node { 4 char c; 5 int index; 6 node(char _c, int _index):c(_c), index(_index){}; 7 }; 8 int longestValidParentheses(string s) { 9 // Start typing your C/C++ solution below 10 // DO NOT write int main() function 11 if (s.size() <= 1) return 0; 12 stack<node> S; 13 int maxlen = 0; 14 S.push(node(')', -1)); 15 int lastlen = 0; 16 for (int i = 0; i < s.size(); i++) { 17 if (s[i] == '(') S.push(node('(', i)); 18 else { 19 node tmp = S.top(); 20 if (tmp.c == '(') { 21 S.pop(); 22 maxlen = max(maxlen, i-S.top().index); 23 } 24 else S.push(node(')', i)); 25 } 26 } 27 return maxlen; 28 } 29 };
C#
1 public class Solution { 2 public class node { 3 public char c; 4 public int index; 5 public node (char _c, int _index) { 6 c = _c; 7 index = _index; 8 } 9 }; 10 public int LongestValidParentheses(string s) { 11 if (s.Length <= 1) return 0; 12 Stack<node> S = new Stack<node>(); 13 int maxLen = 0; 14 S.Push(new node(')', -1)); 15 int lastLen = 0; 16 for (int i = 0; i < s.Length; i++) { 17 if (s[i] == '(') S.Push(new node('(', i)); 18 else { 19 node tmp = S.Peek(); 20 if (tmp.c == '(') { 21 S.Pop(); 22 maxLen = Math.Max(maxLen, i - S.Peek().index); 23 } 24 else S.Push(new node(')', i)); 25 } 26 } 27 return maxLen; 28 } 29 }