Valid Parentheses (leetcode20)
这道题是括号问题的最初阶版本,给出一个字符串,判断括号匹配是否合法。常用的解法就是用栈实现。
初始化一个栈,遇到左括号将其入栈,遇到右括号检查此时的栈顶元素,如果栈顶元素是与之相匹配的左括号,将其推出栈,反之,则字符串一定是不合法的。
The general method is using a stack to solve this problem. Initialize a stack and go through the string. If the character we meet is a left parenthesis, push it into the stack. If not, check the peek of the stack. If the current peek is the corresponding left parenthesis, pop the peek, else return false.
After traversing all the character, return true if the stack is empty, else return false.
public boolean isValid(String s) {
Stack<Character> stack=new Stack<Character>();
for (char c:s.toCharArray()) {
if (c=='('||c=='{'||c=='[')
stack.push(c);
else {
if (stack.empty()) return false;
char top=stack.peek();
if ((c==')'&&top=='(')||(c=='}'&&top=='{')||(c==']'&&top=='[')) {
stack.pop();
continue;
}
return false;
}
}
return stack.isEmpty();
}
Generate Parentheses (leetcode 22)
括号匹配问题的一个进阶版本,输入一个正整数n,要求给出可能的长为n的括号匹配结果。
Generally, all the problems of searching all the permutations, combinations, subsets could be solved by backtracking. The basic logic of backtracking algorithm is to update a current answer variable and a result list variable. If the current answer could meet the requirement, then add the copy of it into the result list.
For this problem, the task is to search all the possible valid permutations. It is obvious that the number of left parentheses and right parentheses are both n/2. We could use backtracking to solve it. The input of recursion function are the current string, result list, the number of left left parentheses, the number of left right parentheses. If left<0 or right<0 or left>right, which means the current string is invalid, return. If the left=0 and right=0, add the current string into the result list.
public void generateParenthesis(List<String> result,StringBuilder curr,int left,int right){
if (left==0&&right==0){
result.add(curr.toString());
return;
}
if (left<0||right<0||left>right) return;
if (left>0){
curr.append('(');
generateParenthesis(result,curr,left-1,right);
curr.delete(curr.length()-1,curr.length());
}
if (right>0){
curr.append(')');
generateParenthesis(result,curr,left,right-1);
curr.delete(curr.length()-1,curr.length());
}
return;
}
public List<String> generateParenthesis(int n) {
List<String> result=new ArrayList<>();
generateParenthesis(result,new StringBuilder(""),n,n);
return result;
}
Longest Valid Parentheses (leetcode 32)
This task asks us to find the length of the longest valid parentheses. Dynamic programming is very helpful for the problems like finding the maximum length of a specific substring. For this problem, we could also use dynamic programming to sosolve it.
Using an array to store the middle result. dp[i] represents the maximum length of thesubstring which is ended at dp[i].
It’sobvious that if s[i]=”(“, dp[i]=0 because the substring which endedwith a left parenthesis must be invalid. If the s[i]=”)”, we shoulddiscuss representatively according to s[i-1]
ifs[i-1]=”(“, dp[i]=dp[i-2]+2 because “()” is a valid substring.If not, consider s[i-dp[i-1]-1], if it is a left parenthesis, then dp[i]=dp[i-1]+dp[i-dp[i-1]-2]+2,else dp[i]=0.
public int longestValidParentheses(String s) {
int[] dp=new int[s.length()];
int max=0;
for (int i=1;i<s.length();i++){
if (s.charAt(i)=='(') dp[i]=0;
else{
if (s.charAt(i-1)=='(') dp[i]=2+(i==1?0:dp[i-2]);
else {
if ((i-dp[i-1]-1>-1)&&s.charAt(i-dp[i-1]-1)=='(')
dp[i]=dp[i-1]+(i-dp[i-1]-1==0?0:dp[i-dp[i-1]-2])+2;
}
}
max=Math.max(max,dp[i]);
}
return max;
}