"Day 43: Solving '20. Valid Parentheses' with Java"

"🚀Day 43 of 50 – Java LeetCode Challenge" Today’s challenge was "20. Valid Parentheses" — a fundamental stack-based problem that strengthens your understanding of bracket matching and data structure usage. The goal is to determine whether a given string of parentheses is valid based on correct opening and closing order. ⏱ Today’s Task – Valid Parentheses 📝 Problem Statement: Given a string s containing just the characters '(', ')', '{', '}', '[', and ']', determine if the input string is valid. ✅ A string is valid if: 1️⃣ Every open bracket has a corresponding closing bracket of the same type. 2️⃣ Brackets are closed in the correct order. 3️⃣ Every close bracket must have an open bracket before it. 🧪 Examples: Input: s = "()" Output: true ✅ Input: s = "()[]{}" Output: true ✅ Input: s = "(]" Output: false ❌ Input: s = "([])" Output: true ✅ Input: s = "([)]" Output: false ❌ 🔧 Constraints: 1 <= s.length <= 10⁴ s consists of parentheses only '()[]{}' 💻 My Java Solution: import java.util.*; class Solution {   public boolean isValid(String s) {     Stack<Character> stack = new Stack<>();     Map<Character, Character> map = new HashMap<>();     map.put(')', '(');     map.put('}', '{');     map.put(']', '[');     for (char c : s.toCharArray()) {       if (map.containsKey(c)) {         char top = stack.isEmpty() ? '#' : stack.pop();         if (top != map.get(c)) return false;       } else {         stack.push(c);       }     }     return stack.isEmpty();   } } 🔍 Takeaways: ✅ Efficient use of a stack for bracket matching ✅ Clean implementation using a HashMap for bracket pairs ✅ Time complexity O(n) — single traversal through the string ✅ Space complexity O(n) — in worst case (all open brackets) 💡 Core Concepts: Stack data structure HashMap for mapping bracket pairs Iterative traversal and validation Balanced parenthesis logic 🎯 Day 43 completed — 7 more to go! 🚀 #Java #50DaysOfCode #LeetCode #ProblemSolving #Stack #DataStructures #Day43 #JavaProgramming #CodeNewbie #LearnInPublic

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories