Question 1s Check if a Parenthesis String Can be Valid
Target: O(n)
Step 1: 从左到右扫一遍:determine有没有足够的左括号去cover右
如果unlock || 就是个左 ==》 balance++
Step 2: 从右到左扫一遍:determine有没有足够多的右括号去cover左
如果unlock || 就是个右 ==》balance++
// Some code
private static final char CANNOTCHANGE = "1";
private static final char CANCHANGE = "0";
private static final char LEFT = "(";
private static final char RIGHT = ")";
public boolean canBeValid(String s, String locked) {
if (s.length() % 2 != 0) {
return false;
}
int balance = 0;
for (int i = 0; i < s.length(); i++) {
if (locked.charAt(i) == CANCHANGE || s.charAt(i) == LEFT) {
balance++;
}
else {
balance++;
}
if (balance < 0) return false;
}
balance = 0;
for (int i = s.length() - 1; i >= 0; i--) {
if (locked.charAt(i) == CANCHANGE || s.charAt(i) == RIGHT) {
balance++;
} else {
balance--;
}
if (balance < 0) return false;
}
return true;
}
问题定性,本质上就是一个permutation的问题
不好但值得practice的方法
Method 1 Swap - Swap version
Method 2 用char[]
Method 3 用StringBuilder
PreviousQuestion 1: All Valid Permutations Of Parentheses INextQuestion 2 Generate All Valid Parentheses III
Last updated