leetcode hard模式专杀之32. Longest Valid Parentheses

xiaoxiao2021-02-27  141

继续leetcode hard模式,这题整了我好久,想了好几种方法,最终都没能通过oj都时间复杂度,然后忍不住看了答案,简洁到尿,想死, 上代码:

import java.util.Stack; public class Solution { public int longestValidParentheses(String str) { int n = str.length(); Stack<Integer> stk = new Stack<>(); stk.push(-1); int result = 0; for (int i=0; i<n; i++) { if (str.charAt(i) == '('){ stk.push(i); }else { stk.pop(); if (!stk.empty()){ result = Math.max(result, i - stk.peek()); } else{ stk.push(i); } } } return result; } }

转载请注明原文地址: https://www.6miu.com/read-13205.html

最新回复(0)