Permalink
Cannot retrieve contributors at this time
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?
LeetCode/valid-parentheses
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
73 lines (62 sloc)
1.64 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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/ |