Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Monday, May 2, 2022

Valid Parentheses Java Solution


Problem:

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 close brackets.
    Open brackets must be closed in the correct order.
 

 

 Solution:

class Solution {
    public boolean isValid(String s) {
     Stack<Character> stack = new Stack<>();
        for(int i=0;i<s.length();++i) {
            if(openingBracket(s, i)) {
                stack.push(s.charAt(i));
            }
            else {
                if(stack.isEmpty()) return false;
                char element = stack.pop();
                if(!OpeningOf(element,s.charAt(i))) return false;
            }
        }
        return stack.isEmpty();
    }
    public boolean openingBracket(String s, int i) {
        char bracket = s.charAt(i);
        if(bracket == '[' || bracket == '(' || bracket == '{' )
            return true;
        return false;
    }
    public boolean OpeningOf(char x, char y) {
        switch(y) {
            case ']' : return x == '[';
            case ')' : return x == '(';
            case '}' : return x == '{';
        }
        return false;
    }
}

0 Comments:

Post a Comment

Stats