Leetcode || Longest Valid Parentheses

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.

Subscribe to see which companies asked this question

package cc.stack.application;

import java.util.Stack;

/*
 * 字符串遍歷,遇"("入棧,遇")"且棧頂是"(",ok一次
 */
class Solution {
    public int longestValidParentheses(String s) {
         if(s == null || s.length() == 0) 
             return 0;
         Stack<String> stack = new Stack<String>();
         int result = 0;
         for(int i=0; i<s.length(); i++) {
             if(s.substring(i, i+1).equals("("))
                 stack.push(s.substring(i, i+1));
             else if(s.substring(i, i+1).equals(")")) {
                 if(!stack.isEmpty()) {
                     if(stack.pop().equals("("))
                         result++;
                 }
             }   
         }
         return result*2;
    }

}



public class Main1 {
    public static void main(String[] args) {
        Solution s = new Solution();
        String tokens = "( ) ( ( ( ) )";
        System.out.println(s.longestValidParentheses(tokens));

    }

}
發佈了227 篇原創文章 · 獲贊 24 · 訪問量 32萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章