Valid Parentheses

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.


An input string is valid if:


Open brackets must be closed by the same type of brackets.

Open brackets must be closed in the correct order.

Every close bracket has a corresponding open bracket of the same type.

 


Example 1:


Input: s = "()"


Output: true


Example 2:


Input: s = "()[]{}"


Output: true


Example 3:


Input: s = "(]"


Output: false


Example 4:


Input: s = "([])"


Output: true


 

Stack-Based Logic:

  1. Traverse each character in the string.

  2. If it's an opening bracket ('(', '{', '['), push it onto the stack.

  3. If it's a closing bracket (')', '}', ']'):

    • If the stack is empty, return false (nothing to match).

    • If the top of the stack is the corresponding opening bracket, pop it.

    • Otherwise, return false.

  4. At the end, if the stack is empty, return true. Else, return false.

class Solution {
    public boolean isValid(String s) {
         Stack<Character> st = new Stack<>();

        for (char ch : s.toCharArray()) {
            if (ch == '(' || ch == '{' || ch == '[') {
                st.push(ch);
            } else {
                if (st.isEmpty()) return false;

                char top = st.pop();
                if ((ch == ')' && top != '(') ||
                    (ch == '}' && top != '{') ||
                    (ch == ']' && top != '[')) {
                    return false;
                }
            }
        }

        return st.isEmpty();
    }
}

 2nd code :



class Solution {
    public boolean isValid(String s) {
        Stack<Character> st = new Stack<>();

        for (char ch : s.toCharArray()) {
            // Push all opening brackets
            if (ch == '(' || ch == '{' || ch == '[') {
                st.push(ch);
            } else {
                // If stack is empty or top doesn't match the closing bracket
                if (st.isEmpty()) return false;

                if ((ch == ')' && st.peek() != '(') ||
                    (ch == '}' && st.peek() != '{') ||
                    (ch == ']' && st.peek() != '[')) {
                    return false;
                }

                st.pop(); // matched pair, remove from stack
            }
        }

        // If stack is empty, all brackets are matched
        return st.isEmpty();
    }
}

Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence