• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ying_vincent
博客园    首页    新随笔    联系   管理    订阅  订阅

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 }
View Code

 

posted @ 2013-04-05 03:41  ying_vincent  阅读(364)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3