Saturday, March 20, 2021

Valid Parentheses

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

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.
 

Example 1:

Input: s = "()"
Output: true

Example 2:

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

Example 3:

Input: s = "(]"
Output: false

Example 4:

Input: s = "([)]"
Output: false

Example 5:

Input: s = "{[]}"
Output: true
Solution:
public boolean isValid(String s) {
        
        Stack<Character> stack = new Stack<Character>();
        char[] arr = s.toCharArray();
        for(int i=0; i<arr.length; i++) {
            char c=arr[i];
            if(c=='(' || c=='{'|| c=='['){
                stack.push(c);
            }
            else if(c==')'){
                if(stack.isEmpty() || '('!=stack.pop()) {
                    return false;
                }
            }
            else if(c=='}'){
                if(stack.isEmpty() || '{'!=stack.pop()) {
                    return false;
                }
            }
            else if(c==']'){
                if(stack.isEmpty() || '['!=stack.pop()) {
                    return false;
                }
            }
        }
        return stack.isEmpty();        
    }

Approach#2

class Solution { // Hash table that takes care of the map. private HashMap<Character, Character> map; // Initialize hash map with mappings. This simply makes the code easier to read. public Solution() { this.map = new HashMap<Character, Character>(); this.map.put(')', '('); this.map.put('}', '{'); this.map.put(']', '['); } public boolean isValid(String s) { // Initialize a stack to be used in the algorithm. Stack<Character> stack = new Stack<Character>(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); // If the current character is a closing bracket. if (map.containsKey(c)) { // Get the top element of the stack. If the stack is empty, set a dummy value '#' char topElement = stack.empty() ? '#' : stack.pop(); // If the mapping for this bracket doesn't match, return false. if (topElement != map.get(c)) { return false; } } else { // If it was an opening bracket, push to the stack. stack.push(c); } } // If the stack still contains elements, then it is an invalid expression. return stack.isEmpty(); } }

No comments:

Post a Comment