Skip to main content

Command Palette

Search for a command to run...

Day 1 - Valid Parentheses

Data Structure: Stack

Published
1 min read
S

An engineer with demonstrated working knowledge on Java, Spring boot and related echo system.

Hola,

This is one of the basic problem which helps us to test our knowledge on Stack DS.

Problem: Valid Parentheses

Solution:

import java.util.Stack;
public class Solution {
    public static boolean isValidParenthesis(String expression) {
        // Write your code here
        Stack<Character> stack = new Stack<>();
        for(char ch : expression.toCharArray()) {
            if (stack.isEmpty() && (ch ==')' || ch == ']' || ch == '}')) {
                return false;
            } else if (!stack.isEmpty() && ((ch ==')' && stack.peek() == '(') || (ch == ']' &&   
                           stack.peek() == '[') || (ch == '}' && stack.peek() == '{'))) {
                stack.pop();
            } else {
                stack.push(ch);
            }
        }
        return stack.isEmpty();
    }
}

If you would like to receive daily notifications on my content, you can join in my telegram group Join In Telegram Group

You can follow me at LinkedIn

Gracias.

Daily DSA

Part 3 of 3

A place where you can find problems on different DSA topics daily.

Start from the beginning

How to get started with Stack Data Structure?

PART - 1