您的位置:首页 > 其它

LeetCode: Longest Valid Parentheses

2013-04-05 03:41 447 查看
用dfs large超时,看了网上答案用stack,其实一开始也想到了,只是没预料到stack比dfs更优越

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: