LeetCode 20. Valid Parentheses

Description

https://leetcode.com/problems/valid-parentheses/

Given a string 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.

Note that an empty string is also considered valid.

Example 1:

Input: "()"
Output: true

Example 2:

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

Example 3:

Input: "(]"
Output: false

Example 4:

Input: "([)]"
Output: false

Example 5:

Input: "{[]}"
Output: true

Explanation

The problem is about validating parenthesis in the input string. The input string contains only '(', ')', '{', '}', '[' and ']'.

By introducing a stack, we could easily solve the problem.

Start from the first position to visit every character in the string:

  • If the character is one left parenthesis, we push it to stack
  • If the character is one right parenthesis, we check if the character matches with the left parenthesis at the top of the stack. If not matched or the stack is empty, the input string fails the test.

Java Solution

public class Solution { 
    public boolean isValid(String s) { 
        Stack<Character> stack = new Stack<Character>(); 
        boolean isValid = false; 
         
        for (int i = 0; i < s.length(); i++) { 
            char ch = s.charAt(i); 
            if (ch == '(' || ch == '{' || ch == '[') { 
                stack.push(ch); 
            } else { 
                if (!stack.isEmpty() && isPair(stack.peek(), ch)) { 
                    stack.pop(); 
                } else { 
                    return false; 
                } 
            } 
        } 
         
        return stack.isEmpty(); 
    } 
 
    private boolean isPairParenthesis(char c1, char c2) { 
        return (c1 == '(' && c2 == ')')  
            || (c1 == '{' && c2 == '}') 
            || (c1 == '[' && c2 == ']'); 
    }     
}


Python Solution

class Solution:
    def isValid(self, s: str) -> bool:
        
        stack = []
        
        for char in s:
            if char == '(' or char == '[' or char == '{':
                stack.append(char)
            else:
                if len(stack) == 0 or (not self.valid_pair(stack[-1], char)):
                    return False
                left = stack.pop()
                                                
        return len(stack) == 0
    
    def valid_pair(self, left, right):        
        return (left == '(' and right == ')' ) or (left == '[' and right == ']' ) or (left == '{' and right == '}')
  • Time complexity: O(N).
  • Space complexity: O(N). 

One Thought to “LeetCode 20. Valid Parentheses”

Leave a Reply

Your email address will not be published. Required fields are marked *