Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

最长有效括号 #50

Open
louzhedong opened this issue Sep 6, 2018 · 0 comments
Open

最长有效括号 #50

louzhedong opened this issue Sep 6, 2018 · 0 comments

Comments

@louzhedong
Copy link
Owner

习题

出处:LeetCode 算法第32题

给定一个只包含 '('')' 的字符串,找出最长的包含有效括号的子串的长度。

示例 1:

输入: "(()"
输出: 2
解释: 最长有效括号子串为 "()"

示例 2:

输入: ")()())"
输出: 4
解释: 最长有效括号子串为 "()()"

思路

使用一个栈来保存最长匹配的字符串,每次遇到匹配的对,如果是和前面连续的,则使最大值加2。并使堆栈弹出两个值。

解答

/**
 * @param {string} s
 * @return {number}
 */
var longestValidParentheses = function (s) {
  var result = 0;
  var arrayStack = [0];
  s.split('').forEach(item => {
    if (item == '(') {
      arrayStack.push(0);
    } else {
      var length = arrayStack.length;
      if (length >= 2) {
        arrayStack[length - 2] += arrayStack.pop() + 2;
        result = Math.max(result, arrayStack[length - 2]);
      } else {
        arrayStack = [0];
      }
    }
  });
  return result;
};

console.log(longestValidParentheses(')(()())'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant