【leetcode】括号符匹配问题(Parentheses):Valid Parentheses|Generate Parentheses|LongestValid Parentheses

来源:互联网 发布:海森堡测不准原理 知乎 编辑:程序博客网 时间:2024/06/05 06:05

leetcode上有三道关于括号符(‘(’,‘)’,‘[’,‘]’,‘{’,‘}’)匹配的问题,其中第三题是第一题的拓展,分别是:

(1)Valid Parentheses,判断字符串是否是合法的括号匹配字符串

(2)Generate Parentheses,根据所给的整数生成所有合法的括号匹配字符串

(3)Longest Valid Parentheses,根据所给的括号字符串,求其中最长的括号匹配字符子串

 下面分别讨论我对这三道题的思路的做法。


题目:Valid Parentheses

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

解析:已知字符串包含‘(’、‘)’、‘[’、‘]’、‘{’、‘}’ 六种字符,判断其是否为合法的字符串,是否合法的标准是每种类型括号的左右括号匹配。主要解法是用“栈”(Stack)来维护当前的字符串,如果遇到三种左括号即‘(’、‘[’、‘{’,直接将当前符号push栈中,如果遇到三种右括号‘)’、‘]’、‘}’,需要判断栈顶层的括号类型是否为匹配的右括号。
Java AC代码:

public class Solution {    public boolean isValid(String s) {        Stack<Character> stack = new Stack<Character>();        for(int i=0;i<s.length();i++){            if(s.charAt(i)==')'||s.charAt(i)==']'||s.charAt(i)=='}'){            if(stack.empty()){            return false;            }            char c = stack.pop();            if((c=='('&&s.charAt(i)!=')')||(c=='['&&s.charAt(i)!=']')||(c=='{'&&s.charAt(i)!='}')){            return false;            }            }else{            stack.push(s.charAt(i));            }        }        if(stack.empty()){        return true;        }        return false;    }}

题目:Generate Parentheses

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

"((()))", "(()())", "(())()", "()(())", "()()()"

解析:输入正整数n表示生成括号的对数,要求输出所有的括号组合(该题只有小括号)。我对于该题的解决思路是用dfs,针对当前的字符串可以选择添加左括号或者右括号。当前括号数中的左括号数小于右括号数,或者左括号书超出n,右括号书超出n,表示这种字符串肯定不符合要求,不继续进行下一次递归。

Java AC代码:

public class Solution {List<String> result = new ArrayList<String>();public List<String> generateParenthesis(int n) {recursion(n, 0, 0, "");return result;}public void recursion(int n, int left, int right, String str) {if (left < right || left>n || right>n) {return;} else if (left == right && left + right == 2 * n) {result.add(str);return;} else {recursion(n,left+1,right,str+"(");recursion(n,left,right+1,str+")");}}}

题目: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.

解析:根据已给字符串判断其中包含的最长字符匹配的子串(只有小括号字符)。该题判断括号字符串有效性的思路可以参照第一题Valid Parentheses,如果是左括号,直接放入“栈”(Stack)中,如果是右括号,判断栈中是否有左括号和自己匹配。

注意和第一题的一个重要区别是该题要计算最长字符匹配的子串的长度,所以栈中应当存放对应的左括号在字符串中的位置。

Java AC代码:

public class Solution {public int longestValidParentheses(String s) {int res = 0, lastLeft = 0;Stack<Integer> stack = new Stack<Integer>();for (int i = 0; i < s.length(); i++) {if (s.charAt(i) == '(') {stack.push(i);} else if (!stack.isEmpty()) {stack.pop();if (stack.empty()) {res = res > (i - lastLeft + 1) ? res : (i - lastLeft + 1);} else {res = res > (i - stack.peek()) ? res : (i - stack.peek());}} else {lastLeft = i + 1;}}return res;}}



0 0
原创粉丝点击