【LeetCode】678. Valid Parenthesis String 解题报告(Python)

标签(空格分隔): LeetCode

作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.me/


题目地址:https://leetcode.com/problems/valid-parenthesis-string/description/

题目描述:

Given a string containing only three types of characters: ‘(‘, ‘)’ and ‘*’, write a function to check whether this string is valid. We define the validity of a string by these rules:

  1. Any left parenthesis ‘(’ must have a corresponding right parenthesis ‘)’.
  2. Any right parenthesis ‘)’ must have a corresponding left parenthesis ‘(‘.
  3. Left parenthesis ‘(’ must go before the corresponding right parenthesis ‘)’.
  4. ‘*’ could be treated as a single right parenthesis ‘)’ or a single left parenthesis ‘(’ or an empty string.
  5. An empty string is also valid.

Example 1:

Input: "()"
Output: True

Example 2:

Input: "(*)"
Output: True

Example 3:

Input: "(*))"
Output: True

Note:

  1. The string size will be in the range [1, 100].

题目大意

判断一个括号表达是是否合法,其中包含了*号,*可以表示(,)或者空字符。

解题方法

看到括号表达式第一感觉肯定是栈了。但是由于*的存在,导致这么做并不合理。

又是我绞尽脑汁也做不出来的题,果然还是书影博客浅显易懂啊!真大神,我跟着学习了不少。

这个思路是这样的:用一个set集合来记录这个表达式中左括号比右括号多的个数。注意,是能够。因此,如果遇到左括号,集合里面的每个元素应该+1;遇到右括号,如果集合里边的>0的元素可以-1;如果遇到*,应该+1,-1或者不运算。看最后这个集合能否包含0,即左括号的个数等于右括号的个数。

那这个算法怎么判断的”)(“呢?巧妙的地方就在于,只有set里面大于0的元素才去-1;因此刚开始set只有0元素,所以)不算数。所以这个方法真的很巧妙。

class Solution(object):
def checkValidString(self, s):
"""
:type s: str
:rtype: bool
"""
old_set = set([0])
for c in s:
new_set = set()
if c == '(':
for t in old_set:
new_set.add(t + 1)
elif c == ')':
for t in old_set:
if t > 0:
new_set.add(t - 1)
elif c == '*':
for t in old_set:
new_set.add(t + 1)
new_set.add(t)
if t > 0:
new_set.add(t - 1)
old_set = new_set
return 0 in old_set

日期

2018 年 6 月 13 日 ———— 腾讯赛圆满结束!两个月修得正果哈哈~~

最新文章

  1. 异步HTTPHandler的实现
  2. HBase 安装
  3. PTA Insert or Merge
  4. Picard 法求方程根
  5. sql语句执行顺序
  6. Linux下配置OpenCV1.0环境
  7. 相邻div实现一个跟着另一个自适应高度示例代码
  8. 自定义view获取宽高
  9. MATLAB中mexFunction函数的接口规范(转载)
  10. eclipse的安装
  11. ZOJ1074 (最大和子矩阵 DP)
  12. ShopEx访问提示Incompatible file format: The encoded file has format major ID 2, whereas the Loader expects 4
  13. - Shell - sort处理大文件(页 1) - ChinaUnix.net
  14. Servlet之文件的上传与下载
  15. The python debugger(PDB)的简介
  16. http请求requestUtils
  17. if else; while; break;continue ----流程控制系列
  18. 科技论文之Latex公式&符号
  19. sql语句事务
  20. FileMaker Server连接SQL Server测试

热门文章

  1. 32-3Sum
  2. Redis集合解决大数据筛选
  3. 【模板】二分图最大匹配(匈牙利算法)/洛谷P3386
  4. 漏洞检测方法如何选?详解源代码与二进制SCA检测原理
  5. day28 进程(Process)
  6. Flink(二)【架构原理,组件,提交流程】
  7. Scala(五)【集合的高级使用】
  8. oracle中的控制语句
  9. linux-源码软件管理-yum配置
  10. 【Linux】【Services】【Package】编译安装