LeetCode Solution - Problem Valid Parentheses

  • 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 brackets.
    • Open brackets must be closed in the correct order.
    • Every close bracket has a corresponding open bracket of the same type.
Example 1:

Input: s = "()"
Output: true
Example 2:

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

Input: s = "(]"
Output: false
Constraints:
  • 1 <= s.length <= 104
  • s consists of parentheses only '()[]{}'.
Solution:

Java:

class Solution {
    public boolean isValid(String s) {
       HashMap<Character, Character> map = new HashMap<>();
       map.put(")", "(");
       map.put("]", "[");
       map.put("}", "{");

       Stack<Character> stack = new Stack<>();
       for (int i = 0; i < s.length(); i++) {
           char curr = s.CharAt(i);
           if (map.containsKey(curr)) {
               char pop = stack.size() != 0 ? stack.pop() : '#';
               if (pop != map.get(curr)){
                   return false;
               }
           } else {
               stack.push(curr)
           }
       }
       return stack.isEmpty();
    }
}
Python:

class Solution:
    def isValid(self, s: str) -> bool:
        while '()' in s or '[]'in s or '{}' in s:
            s = s.replace('()','').replace('[]','').replace('{}','')
        return False if len(s) !=0 else True

No comments:

Post a Comment

You might also like

Deploy your Django web app to Azure Web App using App Service - F1 free plan

In this post, we will look at how we can deploy our Django app using the Microsoft Azure app service - a free plan. You need an Azure accoun...