IT技術小屋

          秋風秋雨,皆入我心

            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理 ::
            38 隨筆 :: 1 文章 :: 19 評論 :: 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.

          本題的主要思路就是標記那些括號是被匹配的。
          我們可以利用一個布爾數組,如果位置為i的值為true,則表示第i個括號是被匹配的,然后我們只需要求連續為true的元素的個數即可。實現代碼如下:
           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 閱讀(769) 評論(0)  編輯  收藏 所屬分類: Leetcode
          主站蜘蛛池模板: 邢台县| 鄯善县| 双牌县| 高雄市| 容城县| 德化县| 红安县| 宝鸡市| 乌兰察布市| 枣强县| 商水县| 旬阳县| 达日县| 金湖县| 和林格尔县| 蒙阴县| 镇康县| 随州市| 清涧县| 北川| 如皋市| 广丰县| 临澧县| 台州市| 承德市| 宝鸡市| 永福县| 鄂托克前旗| 兴城市| 镇坪县| 武安市| 泾川县| 靖江市| 武定县| 肃南| 金山区| 广饶县| 青岛市| 丰顺县| 祁东县| 罗甸县|