Valid Parentheses
LeetCode 20 · సులభం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
Push openers; each closer must match the top.
నేను Valid Parentheses (LeetCode 20) ను ఇలా పరిష్కరించాను — Parentheses / Bracket Matching ప్యాటర్న్లోని ఒక సులభం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.
కింది వివరణ ఇంగ్లీష్లో ఉంది.
Intuition
Every closing bracket must match the most recent unmatched opening bracket — that's last-in-first-out, a stack.
Approach
- 1
Opening bracket → push.
- 2
Closing bracket → pop and check it matches; empty stack → invalid.
- 3
Valid only if the stack is empty at the end.
నేను ఎలా పరిష్కరించాను
Stack matchingPythonO(n) time · O(n) space
class Solution:
def isValid(self, s: str) -> bool:
stack = []
mpp={
"(":")",
"{":"}",
"[":"]"
}
stack = []
for char in s:
if char in mpp:
stack.append(char)
else:
closing_brace = char
if stack:
opening_brace = stack.pop()
if mpp[opening_brace]!=closing_brace:
return False
else:
return False
return True if len(stack)==0 else FalseValid Parentheses — తరచూ అడిగే ప్రశ్నలు
Valid Parentheses వెనుక ఉన్న intuition ఏమిటి?
Every closing bracket must match the most recent unmatched opening bracket — that's last-in-first-out, a stack.
Valid Parentheses (LeetCode 20) ను ఎలా పరిష్కరించాలి?
1. Opening bracket → push. 2. Closing bracket → pop and check it matches; empty stack → invalid. 3. Valid only if the stack is empty at the end.
Valid Parentheses యొక్క time, space complexity ఎంత?
Time: O(n). Space: O(n). (Accepted approach: Stack matching.)
Valid Parentheses లో సాధారణ పొరపాట్లు ఏమిటి?
Leftover openers like '((' make it invalid.