20. Valid Parentheses
Easy
18.3K
1K
Companies

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.
  3. 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 '()[]{}'.
My code:

class Solution: def isValid(self, s: str) -> bool: a='([{' b=')]}' c=[] for i in s: if i in a and s.count(i)!=s.count(b[a.find(i)]):#checks if no.of opening element==no of closing element print(i,b[a.find(i)]) print(s.count(i),s.count(b[a.find(i)])) return False if i in a and s[-1]!=i and b[a.find(i)] in s:#only appends if opening char is not last element and closing element exists c.append(i) elif i in b and len(c)!=0: if a.find(c[-1])==b.find(i): c.pop() else: return False else: return False return True

Others Solution:
class Solution: def isValid(self, s: str) -> bool:
        stack =[ ]
        d={"(": ")","[":"[","{":"}"}
         for i in s:
            if i in d:
                stack.append(i)
            elif not stack or d[stack.pop()]!=i: # not stack gives True if stack is empty
                    return False
        return len(stack)==0 #will give False if element still remains in stack after looping through s

 

Comments

Popular posts from this blog