Pages

Friday, September 26, 2025

Valid parentheses - Stack

 import java.util.*;


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

        for(int i=0; i<s.length(); i++) {
            char ch = s.charAt(i);


            if(ch == '(' || ch == '{' || ch == '[') {
                stack.push(ch);
            } else {
               
                if(stack.isEmpty()) {
                    return false;
                }

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

        return true;
    }
} OUTPUT: True for all cases.

No comments:

Post a Comment

3917. Count Indices With Opposite Parity (Brute Force) O(n2) + Optimized Solution O(n) + tips LEETCODE WEEKLY 500

  class Solution {     public int [] countOppositeParity ( int [] nums ) {          // approach 1 - checks every pair         int n = n...