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

remove duplicates from sorted array - two pointer approach (leetcode)

  class Solution {     public int removeDuplicates ( int [] nums ) {         // base case: return if array have no el.         if ( nums...