Tensorum
YouTubeಕಲಿಯಲು ಪ್ರಾರಂಭಿಸಿ
LeetCode 20 · Parentheses / Bracket Matching

Valid Parentheses

LeetCode 20 · ಸುಲಭ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್‌ಥ್ರೂ

Push openers; each closer must match the top.

ಸುಲಭStringStackBracket Sequences
LeetCode ನಲ್ಲಿ ತೆರೆಯಿರಿ ↗

ನಾನು 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. 1

    Opening bracket → push.

  2. 2

    Closing bracket → pop and check it matches; empty stack → invalid.

  3. 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 False
ಸ್ಟೆಪ್-ಥ್ರೂ ಲೋಡ್ ಆಗುತ್ತಿದೆ…

Valid 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.