Valid Parenthesis String
LeetCode 678 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
Two counters: optimistic opens forward, optimistic closes backward.
నేను Valid Parenthesis String (LeetCode 678) ను ఇలా పరిష్కరించాను — Parentheses / Bracket Matching ప్యాటర్న్లోని ఒక మధ్యస్థం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.
కింది వివరణ ఇంగ్లీష్లో ఉంది.
Intuition
Scan left to right treating every '*' as '(' — if the open count ever goes negative, there are too many ')'. Scan right to left treating every '*' as ')' — if that count goes negative, there are too many '('. Passing both means some assignment works.
Approach
- 1
openCount: +1 for '(' or '*', −1 for ')'.
- 2
closeCount (from the right): +1 for ')' or '*', −1 for '('.
- 3
Either negative → False.
- 4
Earlier version: two stacks of indices.
నేను ఎలా పరిష్కరించాను
Two-direction countingPythonO(n) time · O(1) space
class Solution:
def checkValidString(self, s):
openCount = 0
closeCount = 0
n = len(s)
for i in range(n):
if s[i] == "(" or s[i] == "*":
openCount += 1
else:
openCount -= 1
if s[n - i - 1] == ")" or s[n - i - 1] == "*":
closeCount += 1
else:
closeCount -= 1
if openCount < 0 or closeCount < 0:
return False
return TrueValid Parenthesis String — తరచూ అడిగే ప్రశ్నలు
Valid Parenthesis String వెనుక ఉన్న intuition ఏమిటి?
Scan left to right treating every '*' as '(' — if the open count ever goes negative, there are too many ')'. Scan right to left treating every '*' as ')' — if that count goes negative, there are too many '('. Passing both means some assignment works.
Valid Parenthesis String (LeetCode 678) ను ఎలా పరిష్కరించాలి?
1. openCount: +1 for '(' or '*', −1 for ')'. 2. closeCount (from the right): +1 for ')' or '*', −1 for '('. 3. Either negative → False. 4. Earlier version: two stacks of indices.
Valid Parenthesis String యొక్క time, space complexity ఎంత?
Time: O(n). Space: O(1). (Accepted approach: Two-direction counting.)
Valid Parenthesis String లో సాధారణ పొరపాట్లు ఏమిటి?
A '*' before a '(' can't close it — the stack version checks index order.