Tuesday, September 16, 2014

Longest Valid Parentheses

Problem

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.

Idea

  • 一个stack记录所有没有匹配的{的位置
  • lastPos 记录上个}的位置.
  • 碰到{就把位置插到stack,碰到}就先Pop,然后看看stack是否空,如果空则表示1个{对应1个},则length = i-lastPos。 如果stack不空,则length = i-lefts.top()

  • Solution


    No comments:

    Post a Comment