查找字符串中最长的有效括号序列的长度,以O(n)时间为单位

编程入门 行业动态 更新时间:2024-10-09 20:25:22
本文介绍了查找字符串中最长的有效括号序列的长度,以O(n)时间为单位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的朋友在一次采访中遇到一个问题,他被告知有O(n)解决方案.但是,我们两个都没有想过.这是问题:

My friend ran into a question in an interview and he was told that there is an O(n) solution. However, neither of us can think it up. Here is the question:

有一个仅包含(和)的字符串,查找最长有效括号子字符串的长度,该字符串应格式正确.

There is a string which contains just ( and ), find the length of the longest valid parentheses substring, which should be well formed.

例如)()())" ,最长的有效括号是()(),长度为4.

For example ")()())", the longest valid parentheses is ()() and the length is 4.

我通过动态编程解决了这个问题,但不是O(n).有什么想法吗?

I figured it out with dynamic programming, but it is not O(n). Any ideas?

public int getLongestLen(String s) { if (s == null || s.length() == 0) return 0; int len = s.length(), maxLen = 0; boolean[][] isValid = new boolean[len][len]; for (int l = 2; l < len; l *= 2) for (int start = 0; start <= len - l; start++) { if ((s.charAt(start) == '(' && s.charAt(start + l - 1) == ')') && (l == 2 || isValid[start+1][start+l-2])) { isValid[start][start+l-1] = true; maxLen = Math.max(maxLen, l); } } return maxLen; }

推荐答案

我之前曾做过这个问题,在压力下提出O(n)解决方案并不容易.就是这个,这是通过堆栈解决的.

I did this question before, and it is not easy to come up with O(n) solution under pressure. Here is it, which is solved with stack.

private int getLongestLenByStack(String s) { //use last to store the last matched index int len = s.length(), maxLen = 0, last = -1; if (len == 0 || len == 1) return 0; //use this stack to store the index of '(' Stack<Integer> stack = new Stack<Integer>(); for (int i = 0; i < len; i++) { if (s.charAt(i) == '(') stack.push(i); else { //if stack is empty, it means that we already found a complete valid combo //update the last index. if (stack.isEmpty()) { last = i; } else { stack.pop(); //found a complete valid combo and calculate max length if (stack.isEmpty()) maxLen = Math.max(maxLen, i - last); else //calculate current max length maxLen = Math.max(maxLen, i - stack.peek()); } } } return maxLen; }

更多推荐

查找字符串中最长的有效括号序列的长度,以O(n)时间为单位

本文发布于:2023-11-30 07:26:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649164.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:括号   时间为   字符串   序列   长度

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!