zoukankan      html  css  js  c++  java
  • [LeetCode] Longest Valid Parentheses

    Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

    For "(()", the longest valid parentheses substring is "()", which has length = 2.

    Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.

    Another string matching problem, this time I finish this problem in 30 minutes! and got ACCEPTED on my first submission. damn thats feels so good.
    I discoverd an easy way to deal with it which I called it "mark&count" I'll explain it below, its easy and I think everyone could understand it.

    init an array r with same size of string, containing int. 
    iterate the string with index variable i
    use stack for pair matching, that is, pushing the index in whenever encounter '(' and pop when ')' . 
    when pop, mark all the position from stack.top() to i in r
    after iterate finish, begin iterate r, count for longest marked position then thats the answer.

    AC:

     1 class Solution {
     2 public:
     3     int longestValidParentheses(string s) {
     4             stack<int> t;
     5     int len = s.size();
     6     vector<int> r(len, 0);
     7     
     8     for (int i=0; i<len; i++){
     9         if (s[i] == '('){
    10             t.push(i);
    11         }
    12         else if (s[i] == ')'){
    13             if (!t.empty()){
    14                 int top = t.top();
    15                 t.pop();
    16                 for (int j=top; j<i+1; j++){
    17                     r[j] = 1;
    18                 }
    19             }
    20         }
    21     }
    22     int max=0,sum=0;
    23     for (int i=0; i<len; i++){
    24         if (r[i]){
    25             if (++sum > max){
    26                 max = sum;
    27             }
    28         }else{
    29             sum = 0;
    30         }
    31     }
    32     return max;
    33     }
    34 };
  • 相关阅读:
    Java之路---Day09(继承)
    Java之路---Day08
    Java之路---Day07
    Java之路---Day06
    转载:js 创建对象、属性、方法
    Javascript类型检测
    jQuery 如何写插件
    js浮点数精度问题
    IE7.JS解决IE兼容性问题方法
    CSS 中文字体的英文名称 (simhei, simsun) 宋体 微软雅黑
  • 原文地址:https://www.cnblogs.com/agentgamer/p/3683959.html
Copyright © 2011-2022 走看看