LeetCode: Longest Valid Parentheses
2013-04-05 03:41
447 查看
用dfs large超时,看了网上答案用stack,其实一开始也想到了,只是没预料到stack比dfs更优越
C#
View Code
class Solution { public: struct node { char c; int index; node(char _c, int _index):c(_c), index(_index){}; }; int longestValidParentheses(string s) { // Start typing your C/C++ solution below // DO NOT write int main() function if (s.size() <= 1) return 0; stack<node> S; int maxlen = 0; S.push(node(')', -1)); int lastlen = 0; for (int i = 0; i < s.size(); i++) { if (s[i] == '(') S.push(node('(', i)); else { node tmp = S.top(); if (tmp.c == '(') { S.pop(); maxlen = max(maxlen, i-S.top().index); } else S.push(node(')', i)); } } return maxlen; } };
C#
public class Solution { public class node { public char c; public int index; public node (char _c, int _index) { c = _c; index = _index; } }; public int LongestValidParentheses(string s) { if (s.Length <= 1) return 0; Stack<node> S = new Stack<node>(); int maxLen = 0; S.Push(new node(')', -1)); int lastLen = 0; for (int i = 0; i < s.Length; i++) { if (s[i] == '(') S.Push(new node('(', i)); else { node tmp = S.Peek(); if (tmp.c == '(') { S.Pop(); maxLen = Math.Max(maxLen, i - S.Peek().index); } else S.Push(new node(')', i)); } } return maxLen; } }
View Code
相关文章推荐
- leetcode: Longest Valid Parentheses
- Java [leetcode 32]Longest Valid Parentheses
- [leetcode]Longest Valid Parentheses
- leetcode 32. Longest Valid Parentheses
- LeetCode-32. Longest Valid Parentheses
- 【LeetCode练习题】Longest Valid Parentheses
- LeetCode - 32. Longest Valid Parentheses
- LeetCode032 Longest Valid Parentheses
- LeetCode Longest Valid Parentheses
- LeetCode算法题目:Longest Valid Parentheses
- LeetCode 032 Longest Valid Parentheses
- LeetCode 笔记系列八 Longest Valid Parentheses [lich你又想多了]
- LeetCode | 32. Longest Valid Parentheses——最长有效括号匹配长度
- LeetCode----Longest Valid Parentheses
- LeetCode-Longest Valid Parentheses
- LeetCode (32) Longest Valid Parentheses
- [LeetCode]Longest Valid Parentheses
- LeetCode - 32. Longest Valid Parentheses
- Leetcode: Longest Valid Parentheses
- [leetcode] Longest Valid Parentheses