IT技術(shù)小屋

          秋風(fēng)秋雨,皆入我心

            BlogJava :: 首頁 :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理 ::
            38 隨筆 :: 1 文章 :: 19 評(píng)論 :: 0 Trackbacks
          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.

          本題的主要思路就是標(biāo)記那些括號(hào)是被匹配的。
          我們可以利用一個(gè)布爾數(shù)組,如果位置為i的值為true,則表示第i個(gè)括號(hào)是被匹配的,然后我們只需要求連續(xù)為true的元素的個(gè)數(shù)即可。實(shí)現(xiàn)代碼如下:
           1 public class LongestValidParentheses {
           2     public int longestValidParentheses(String s) {
           3         int length = s.length();
           4         if (length == 0)
           5             return 0;
           6         int left = 0;
           7         Stack<Integer> indexs = new Stack<Integer>();
           8         boolean[] record = new boolean[length];
           9         for (int i = 0; i < length; i++) {
          10             if (s.charAt(i) == '(') {
          11                 left++;
          12                 indexs.push(i);
          13             } else if (left > 0) {
          14                 int idx = indexs.pop();
          15                 record[idx] = true;
          16                 record[i] = true;
          17                 left--;
          18             }
          19         }
          20         int ret = 0;
          21         int current = 0;
          22         for (int k = 0; k < length; k++) {
          23             if (record[k]) {
          24                 current++;
          25             } else {
          26                 ret = current > ret ? current : ret;
          27                 current = 0;
          28             }
          29         }
          30         return ret > current ? ret : current;
          31     }
          32 }
          posted on 2013-12-21 21:28 Meng Lee 閱讀(774) 評(píng)論(0)  編輯  收藏 所屬分類: Leetcode
          主站蜘蛛池模板: 叙永县| 荆门市| 秦安县| 保山市| 郑州市| 乳源| 休宁县| 元江| 桓台县| 灵武市| 阿拉善盟| 论坛| 平远县| 轮台县| 海城市| 聂拉木县| 锦州市| 磴口县| 常州市| 泰来县| 三门县| 伊金霍洛旗| 尤溪县| 苏尼特右旗| 大城县| 昭苏县| 通江县| 蒙城县| 共和县| 全南县| 同仁县| 兴化市| 尼玛县| 铁力市| 电白县| 弥渡县| 米泉市| 潞城市| 商城县| 凭祥市| 兰州市|