leetcode python3 简单题20. Valid Parentheses
1.编辑器
我使用的是win10+vscode+leetcode+python3
环境配置参见我的博客:
链接
2.第二十题
(1)题目
英文:
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.
中文:
给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses
(2)解法(耗时:36ms,内存:13.7M)
使用栈入栈出的思想
class Solution:def isValid(self, s: str) -> bool:match = {')':'(', ']':'[', '}':'{'}stack = []for char in s:if char not in match:stack.append(char)else:if not stack or stack[-1]!=match[char]:return Falsestack.pop(-1)return len(stack) == 0
注意:
1.pop可以指定index位被移出stack,当然也可以用del stack[-1]
。
2.因为程序中最开始是要判断char是否在match中的keys中的,如果不在则直接加到stack中,如果在,就比较前一个左括号是否与match[char]相同,相同则配对成功,并且要删除掉左括号,当所有的左括号都删完了还没有False,则输出True。
leetcode python3 简单题20. Valid Parentheses相关推荐
- leetcode python3 简单题125. Valid Palindrome
1.编辑器 我使用的是win10+vscode+leetcode+python3 环境配置参见我的博客: 链接 2.第一百二十五题 (1)题目 英文: Given a string, determin ...
- leetcode python3 简单题231. Power of Two
1.编辑器 我使用的是win10+vscode+leetcode+python3 环境配置参见我的博客: 链接 2.第二百三十一题 (1)题目 英文: Given an integer, write ...
- leetcode python3 简单题225. Implement Stack using Queues
1.编辑器 我使用的是win10+vscode+leetcode+python3 环境配置参见我的博客: 链接 2.第二百二十五题 (1)题目 英文: Implement the following ...
- leetcode python3 简单题168. Excel Sheet Column Title
1.编辑器 我使用的是win10+vscode+leetcode+python3 环境配置参见我的博客: 链接 2.第一百六十八题 (1)题目 英文: Given a positive integer ...
- leetcode python3 简单题70. Climbing Stairs
1.编辑器 我使用的是win10+vscode+leetcode+python3 环境配置参见我的博客: 链接 2.第七十题 (1)题目 英文: You are climbing a stair ca ...
- leetcode python3 简单题69. Sqrt(x)
1.编辑器 我使用的是win10+vscode+leetcode+python3 环境配置参见我的博客: 链接 2.第六十九题 (1)题目 英文: Implement int sqrt(int x). ...
- leetcode python3 简单题53. Maximum Subarray
1.编辑器 我使用的是win10+vscode+leetcode+python3 环境配置参见我的博客: 链接 2.第五十三题 (1)题目 英文: Given an integer array num ...
- leetcode python3 简单题58. Length of Last Word
1.编辑器 我使用的是win10+vscode+leetcode+python3 环境配置参见我的博客: 链接 2.第五十八题 (1)题目 英文: Given a string s consists ...
- leetcode python3 简单题38. Count and Say
1.编辑器 我使用的是win10+vscode+leetcode+python3 环境配置参见我的博客: 链接 2.第三十八题 (1)题目 英文: Given an integer n where 1 ...
最新文章
- linux 中关于网络的配置方法
- jenkins 邮件配置 二 ***
- Sqoop_ 简单介绍
- VMware安装MikroTik RouterOS chr
- 程序员法律考试(5)-民法(2)
- 黎明之路服务器正在维护,黎明之路进不去怎么办_黎明之路更新失败怎么办_玩游戏网...
- Mybatis resultMap空值映射问题解决
- iOS 11 适配集锦
- python webservices_python实现webservices接口并调用
- 【数据科学系统学习】机器学习算法 # 西瓜书学习记录 [9] 决策树
- 软件性能分析与优化详解
- 用谷歌浏览器下载网页视频
- 0ctf – mobile – boomshakalaka writeup
- 关系型数据库设计——银行业务管理系统
- 记一次git pull 错误
- 关于大数据相关的问答汇总,持续更新中~
- C++ endl 详解
- 关于计算机运行管理模式,浅谈学校计算机机房管理及维护运行模式.docx
- Navicat Premium的下载及安装
- 在实体PC机上安装Linux系统