1+ package com .thealgorithms .stacks ;
2+
3+ import java .util .HashMap ;
4+ import java .util .Map ;
5+ import java .util .Stack ;
6+
7+ /**
8+ * Valid Parentheses Problem
9+ *
10+ * Given a string containing just the characters '(', ')', '{', '}', '[' and ']',
11+ * determine if the input string is valid.
12+ *
13+ * An input string is valid if:
14+ * 1. Open brackets must be closed by the same type of brackets.
15+ * 2. Open brackets must be closed in the correct order.
16+ * 3. Every close bracket has a corresponding open bracket of the same type.
17+ *
18+ * Examples:
19+ * Input: "()"
20+ * Output: true
21+ *
22+ * Input: "()[]{}"
23+ * Output: true
24+ *
25+ * Input: "(]"
26+ * Output: false
27+ *
28+ * Input: "([)]"
29+ * Output: false
30+ *
31+ * @author Gokul45-45
32+ */
33+ public final class ValidParentheses {
34+ private ValidParentheses () {
35+ }
36+
37+ /**
38+ * Checks if the given string has valid parentheses
39+ *
40+ * @param s the input string containing parentheses
41+ * @return true if valid, false otherwise
42+ */
43+ public static boolean isValid (String s ) {
44+ if (s == null || s .length () % 2 != 0 ) {
45+ return false ;
46+ }
47+
48+ Map <Character , Character > parenthesesMap = new HashMap <>();
49+ parenthesesMap .put ('(' , ')' );
50+ parenthesesMap .put ('{' , '}' );
51+ parenthesesMap .put ('[' , ']' );
52+
53+ Stack <Character > stack = new Stack <>();
54+
55+ for (char c : s .toCharArray ()) {
56+ if (parenthesesMap .containsKey (c )) {
57+ // Opening bracket - push to stack
58+ stack .push (c );
59+ } else {
60+ // Closing bracket - check if it matches
61+ if (stack .isEmpty ()) {
62+ return false ;
63+ }
64+ char openBracket = stack .pop ();
65+ if (parenthesesMap .get (openBracket ) != c ) {
66+ return false ;
67+ }
68+ }
69+ }
70+
71+ // Stack should be empty if all brackets are matched
72+ return stack .isEmpty ();
73+ }
74+ }
0 commit comments