30-Day Leetcoding Challenge Day16
解法一:正反各遍历一次。正向遍历只要保证( 加 *的数量大于)。反向遍历保证* 加 )的数量大于(。
JAVA
class Solution { public boolean checkValidString(String s) { int left = 0; int right = 0; for(int i = 0; i < s.length(); i++){ if(s.charAt(i) == ')'){ left--; } else{ left++; } if(left < 0)return false; } for(int i = s.length()-1; i >= 0; i--){ if(s.charAt(i) == '('){ right--; } else{ right++; } if(right < 0)return false; } return true; } }
Python3
class Solution: def checkValidString(self, s: str) -> bool: left = 0 right = 0 for i in range(len(s)): if s[i] == ')': left -= 1 else: left += 1 if left < 0: return False if left == 0 : return True #bug 应对这种输入'(' for j in range(len(s)-1,-1,-1): if s[j] == '(': right -= 1 else: right += 1 if right < 0: return False return True