# 2116. Check if a Parentheses String Can Be Valid ###### tags: `Leetcode` `Medium` `Parentheses` Link: https://leetcode.com/problems/check-if-a-parentheses-string-can-be-valid/description/ ## 思路 思路参考[这里](https://leetcode.com/problems/check-if-a-parentheses-string-can-be-valid/solutions/1646594/left-to-right-and-right-to-left/) 先从左到右扫描看有没有孤儿')' 再从右到左扫描看有没有孤儿'(' ## Code ```python= class Solution: def canBeValid(self, s: str, locked: str) -> bool: def validate(s: str, locked: str, op: str) -> bool: lockedScore = 0 unlockedCnt = 0 for i in range(len(s)): if locked[i]=="1": lockedScore += 1 if s[i]==op else -1 else: unlockedCnt += 1 if lockedScore+unlockedCnt<0: return False return unlockedCnt>=lockedScore return len(s)%2==0 and validate(s, locked, '(') and validate(s[::-1], locked[::-1], ')') ```