← All problems

2116. Check If a Parentheses String Can Be Valid

MediumOpen on LeetCodeProblem statement

Problem Statement

2116. Check if a Parentheses String Can Be Valid

Medium


A parentheses string is a non-empty string consisting only of '(' and ')'. It is valid if any of the following conditions is true:

You are given a parentheses string s and a string locked, both of length n. locked is a binary string consisting only of '0's and '1's. For each index i of locked,

Return true if you can make s a valid parentheses string. Otherwise, return false.

 

Example 1:

Input: s = "))()))", locked = "010100"
Output: true
Explanation: locked[1] == '1' and locked[3] == '1', so we cannot change s[1] or s[3].
We change s[0] and s[4] to '(' while leaving s[2] and s[5] unchanged to make s valid.

Example 2:

Input: s = "()()", locked = "0000"
Output: true
Explanation: We do not need to make any changes because s is already valid.

Example 3:

Input: s = ")", locked = "0"
Output: false
Explanation: locked permits us to change s[0]. 
Changing s[0] to either '(' or ')' will not make s valid.

 

Constraints:

Java

Source file
class Solution {
    public boolean canBeValid(String s, String locked) {
        int n = s.length(), openCt = 0, liquidCt = 0;
        if (n % 2 == 1)
            return false;
        for (int i = 0; i < n; i++) {
            if (locked.charAt(i) == '0')
                liquidCt++;
            else if (s.charAt(i) == '(')
                openCt++;
            else {
                if (openCt > 0)
                    openCt--;
                else if (liquidCt > 0)
                    liquidCt--;
                else
                    return false;
            }
        }
        // Do the same but in reverse (to check validity of open parentheses)
        openCt = 0;
        liquidCt = 0;
        for (int i = n - 1; i >= 0; i--) {
            if (locked.charAt(i) == '0')
                liquidCt++;
            else if (s.charAt(i) == ')')
                openCt++;
            else {
                if (openCt > 0)
                    openCt--;
                else if (liquidCt > 0)
                    liquidCt--;
                else
                    return false;
            }
        }
        // System.out.println(openCt + "\t" + liquidCt);
        return true;
    }
}