Question 1s Check if a Parenthesis String Can be Valid
// 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;
}
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