Leetcode || Longest Valid Parentheses

来源:互联网 发布:什么是原油数据库存 编辑:程序博客网 时间:2024/06/14 02:16

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));    }}
0 0
原创粉丝点击