bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 2116. Check if a Parentheses String Can Be Valid

2116. Check if a Parentheses String Can Be Valid

Leetcode Solutions

Left-to-right and right-to-left validation

  1. Check if the length of the string s is even. If not, return false because a valid parentheses string must have an even number of characters.
  2. Define a helper function validate that takes the string s, the locked string, and a character op representing the opening parenthesis.
  3. Initialize bal (balance) and wild (wildcards) to 0.
  4. Iterate through the string s:
    • If the current character is locked and matches op, increment bal.
    • If the current character is locked and does not match op, decrement bal.
    • If the current character is unlocked, increment wild.
    • If at any point bal + wild is negative, return false.
    • After the iteration, if bal is greater than wild, return false.
  5. Call the validate function twice: once with the original strings and op as '(', and once with the reversed strings and op as ')'.
  6. If both calls to validate return true, the string can be made valid, so return true. Otherwise, return false.
UML Thumbnail

Counting Brackets

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...