【LeetCode】括号配对系列
来源:互联网 发布:练耳大师 mac 破解 编辑:程序博客网 时间:2024/05/16 05:03
20. Valid Parentheses
题目:判断输入字符串的括号配对是否合法
思路:栈——当前字符为左括号时入栈,右括号则pop一个字符,看是否配对。需要注意栈为空的判断,在pop之前以及最后判断时。
public class Solution { public boolean isValid(String s) { Stack<Character> stack = new Stack<>(); for(int i = 0; i < s.length(); i++){ char c = s.charAt(i); if(c == '(' || c == '[' || c == '{'){ stack.push(c); } else{ if(stack.isEmpty()) return false; char p = stack.pop(); if(c == ')'){ if(p != '(') return false; } else if(c == ']'){ if(p != '[') return false; } else{ if(p != '{') return false; } } } if(!stack.isEmpty()) return false; return true; }}
题目:输出所有合法的括号匹配形式
思路:dfs——分别判断左右括号个数,左括号数小于n,右括号数小于左括号数。有点类似于二叉树的左右子数。
public class Solution { public List<String> generateParenthesis(int n) { List<String> ret = new LinkedList<>(); if(n < 1) return ret; String sb = new String("("); dfs(ret, sb, 1, 0,n); return ret; } public void dfs(List<String> ret, String sb, int left, int right, int n){ if(sb.length() >= 2*n){ ret.add(sb.toString()); return; } else{ if(left < n){ dfs(ret, sb+"(", left+1, right, n); } if(right < left){ dfs(ret, sb+")", left, right+1, n); } } }}
32. Longest Valid Parentheses
题目:找到最长的合法括号配对子串长度。
思路:栈——沿用20题的思路,但是栈中压入的是括号的序号,出现配对就弹出。即栈中每两位之间下表差都是合法的长度,只要找到最大的长度就行。需要注意首尾的判断。
public class Solution { public int longestValidParentheses(String s) { int ret = 0; int len = s.length(); Stack<Integer> stack = new Stack<>(); for(int i = 0; i < len; i++){ if(s.charAt(i) == ')'){ if(!stack.isEmpty() && s.charAt(stack.peek()) == '('){ stack.pop(); continue; } } stack.push(i); } int current = len; if(stack.isEmpty()) return len; while(!stack.isEmpty()){ current = current - stack.peek() - 1; ret = Math.max(ret, current); current = stack.pop(); } return Math.max(ret, current); }}
还可以用动态规划来做。
0 0
- 【LeetCode】括号配对系列
- LeetCode Valid Parentheses判断括号是否配对
- 括号配对
- 括号配对
- 括号配对
- 括号配对
- 括号配对
- 括号配对
- 括号配对
- 括号配对
- 括号配对
- 括号配对
- 括号配对
- 括号配对
- 括号配对
- 括号配对
- 括号配对
- 括号配对
- 在vue中获取dom元素
- jQuery 选择器
- jq 第五章
- 更好用的仿微信、QQ弹框控件
- MySQL8小时的解决方案
- 【LeetCode】括号配对系列
- 记录一下触发器的写法
- CURL常用命令
- Android基础学习之RecylerView学习
- Android进阶之路
- hdu1358 Period
- 拦截一切的CoordinatorLayout Behavior
- 使用TensorFlow实现RNN模型入门篇1
- JavaScript美团选项栏