Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
Given a string 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.
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
My code:
class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack=[]
for i in range(len(s)):
if s[i]=='(':
stack.append(s[i])
if s[i]=='{':
stack.append(s[i])
if s[i]=='[':
stack.append(s[i])
if s[i]==')':
if len(stack)==0:
return False
if stack[-1]=='(':
stack.pop(-1)
else:
return False
if s[i]==']':
if len(stack)==0:
return False
if stack[-1]=='[':
stack.pop(-1)
else:
return False
if s[i]=='}':
if len(stack)==0:
return False
if stack[-1]=='{':
stack.pop(-1)
else:
return False
if len(stack)==0:
return True
else:
return False
Solution:
https://leetcode.com/problems/valid-parentheses/