leetcode_day01
2024-09-06 05:55:02
任务一:有效的括号
题目链接:https://leetcode-cn.com/problems/valid-parentheses/
自己的答案:
class Solution:
def isValid(self, s):
s = list(s)
length = len(s) #空字符串被认为是有效字符串
if length == 0:
return True stringList = ['(', ')', '[', ']', '{', '}']
for s_element in s:
if s_element not in stringList:
return False counter1 = 0
counter2 = 0
counter3 = 0
for s_ele in s:
if s_ele == "(":
counter1 += 1
elif s_ele == ")":
counter1 -= 1
elif s_ele == "[":
counter2 += 1
elif s_ele == "]":
counter2 -= 1
elif s_ele == "{":
counter3 += 1
elif s_ele == "}":
counter3 -= 1
if counter1 == 0 and counter2 == 0 and counter3 == 0:
return True
else:
return False
官方答案:
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
""" # The stack to keep track of opening brackets.
stack = [] # Hash map for keeping track of mappings. This keeps the code very clean.
# Also makes adding more types of parenthesis easier
mapping = {")": "(", "}": "{", "]": "["} # For every bracket in the expression.
for char in s: # If the character is an closing bracket
if char in mapping: # Pop the topmost element from the stack, if it is non empty
# Otherwise assign a dummy value of '#' to the top_element variable
top_element = stack.pop() if stack else '#' # The mapping for the opening bracket in our hash and the top
# element of the stack don't match, return False
if mapping[char] != top_element:
return False
else:
# We have an opening bracket, simply push it onto the stack.
stack.append(char) # In the end, if the stack is empty, then we have a valid expression.
# The stack won't be empty for cases like ((()
return not stack
最新文章
- UIImagePickerControllerDelegate---ActionSheet---获得设备型号
- python开启简单webserver
- HoverTree菜单0.1.3新增效果
- C++输入输出
- centos时间同步方法
- sdutoj 2154 Shopping
- Brush Mode --- Nyoj 236 分类: Brush Mode 2014-04-02 06:56 116人阅读 评论(0) 收藏
- 在PyQt4中使用matplotlib
- Android开发之漫漫长途 XII——Fragment详解
- django drf 开发 ~ models基础学习
- spring cloud_1_mm_eureka2 eureka集群
- 用函数式编程对JavaScript进行断舍离
- 002.MongoDB社区版安装
- docker 2 容器数据卷
- 启动studio报错Gradle error
- FreeMarker快速入门
- SpringBoot集成Jersey
- C#找出接口的所有实现类并遍历执行这些类的公共方法
- ES6的新增数据类型:Symbol
- centos7 禁用每次sudo 需要输入密码
热门文章
- 2018.9.9 Tomcat是怎样运行的
- Java 字符串转码工具类
- Spring MVC的一些学习笔记-入门配置和HttpMessageConverter
- Mac下安装OpenCV3.0和Anaconda和环境变量设置
- C#操作Word,写数据,插入图片
- td过长,将固定宽度table撑开
- 如何使用MongoDB+Springboot实现分布式ID?
- java基础 序列化反序列化流 实现Serializable 接口 自动装载序列号到对象文本文件如修改不能反序列化对象文本,除非自定义long型常量 打印流
- AsyncDisplayKit技术分析
- MySQL 5.7传统复制到GTID在线切换(一主一从)