Problem

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

Example 

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.

JavaScript Code

function longestValidParentheses(s) {
    var stack = [];
    var result = 0;
 
    for(var i=0; i<=s.length-1; i++){
        var c = s.charAt(i);
        if(c=='('){
            var a = [i,0];
            stack.push(a);
        }else{
            if(stack.length == 0||stack[stack.length - 1][1]==1){
                var a = [i,1];
                stack.push(a);
            }else{
                var temp = stack.pop();
                var currentLen=0;
                if(stack.length == 0){
                    currentLen = i+1;
                }else{
                    currentLen = i-stack[stack.length - 1][0];
                }
                result = Math.max(result, currentLen);
            }
        }
    }
 
    return result;
}

1 comment:

  1. PDC Cutters for Stone - As a global Contract Research Organization (CRO), headquartered in New York, USA, Alfa Chemistry has served the pharmaceutical, biotechnology and material industries for years. Today, Alfa Chemistry is the world's leading manufacturer and marketer in the design, development and production of synthetic diamond and cubic boron nitride (CBN). Our high-quality synthetic diamond and cubic boron nitride with full of specifications and sizes are widely used in automotive, consumer electronics, aerospace, intelligent manufacturing and many other high-end processing fields.

    ReplyDelete

Blogroll

Popular Posts