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.
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;
}
}
本文详细探讨了LeetCode上的三道括号匹配问题,包括判断字符串是否为合法括号匹配、生成所有合法括号组合以及找到最长有效括号子串的解决方案。通过递归和栈数据结构来解决这些问题,并提供了Java实现的AC代码。
232

被折叠的 条评论
为什么被折叠?



