அல்கோரிதம்stack matching

Stack matching — nested / paired

TT
Testlaa Team
May 14, 20261 min read

Opener-க்கு order-இல் closer. stack — காத்திருப்பு.

Try this in Python

def valid(s: str) -> bool:
    st: list[str] = []
    pairs = {")": "(", "}": "{", "]": "["}
    for ch in s:
        if ch in "({[":
            st.append(ch)
        elif ch in pairs:
            if not st or st.pop() != pairs[ch]:
                return False
        else:
            return False
    return not st


print(valid("([])"), valid("([)]"))

Key takeaways

  • pop mismatch — invalid.
  • Real parser-ல் வேறு chars.
  • XML/HTML tag-க்கும் skeleton.

Tags:

Stacks & queuesPythonமாணவர்கள்