20. Valid Parentheses
Easy
6619269Add to ListShare
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.
Example 1:
Input: s = "()" Output: true
Example 2:
Input: s = "()[]{}" Output: true
Example 3:
Input: s = "(]" Output: false
Example 4:
Input: s = "([)]" Output: false
Example 5:
Input: s = "{[]}" Output: true
Constraints:
- 1 <= s.length <= 104
- s consists of parentheses only '()[]{}'.
max length는 왜 필요한지 모르겠다..
class Solution:
def isValid(self, s: str) -> bool:
if len(s) == 1:
return False
pairs = {")":"(", "}":"{", "]":"["}
open_p = ["(","{","["]
stack = []
for e in s:
if e in open_p:
stack.append(e)
else:
if stack:
if stack[-1] == pairs[e]:
stack.pop()
else:
stack.append(e)
else:
stack.append(e)
if not stack:
return True
else:
return False
길이가 1일 때 실패, stack이 아무것도 없을 때 -1로 마지막 element 읽어 오면서 fail나서 총 두번 실패.
Success
Runtime: 32 ms, faster than 63.36% of Python3 online submissions for Valid Parentheses.
Memory Usage: 14.3 MB, less than 67.00% of Python3 online submissions for Valid Parentheses.
Next challenges:
Generate ParenthesesLongest Valid ParenthesesRemove Invalid ParenthesesCheck If Word Is Valid After Substitutions
Show off your acceptance:
Time SubmittedStatusRuntimeMemoryLanguage
01/22/2021 00:47 | Accepted | 32 ms | 14.3 MB | python3 |
01/22/2021 00:45 | Runtime Error | N/A | N/A | python3 |
01/22/2021 00:44 | Runtime Error | N/A | N/A | python3 |
'공부하며놀자 > 프로그래밍' 카테고리의 다른 글
Visual Studio Code Python pip install 설정하기 (0) | 2021.12.15 |
---|---|
정보를 받아서 보여주는 웹 Web Application 만들기 heroku github nodejs (0) | 2021.02.04 |
[leetcode] 14. Longest Common Prefix (0) | 2021.01.16 |
[leetcode] 13. Roman to Integer (0) | 2021.01.16 |
[leetcode] 9. Palindrome Number (0) | 2021.01.15 |
댓글