【leetcode】1111. Maximum Nesting Depth of Two Valid Parentheses Strings
题目如下:
A string is a valid parentheses string (denoted VPS) if and only if it consists of
"("
and")"
characters only, and:
- It is the empty string, or
- It can be written as
AB
(A
concatenated withB
), whereA
andB
are VPS's, or- It can be written as
(A)
, whereA
is a VPS.We can similarly define the nesting depth
depth(S)
of any VPSS
as follows:
depth("") = 0
depth(A + B) = max(depth(A), depth(B))
, whereA
andB
are VPS'sdepth("(" + A + ")") = 1 + depth(A)
, whereA
is a VPS.For example,
""
,"()()"
, and"()(()())"
are VPS's (with nesting depths 0, 1, and 2), and")("
and"(()"
are not VPS's.Given a VPS seq, split it into two disjoint subsequences
A
andB
, such thatA
andB
are VPS's (andA.length + B.length = seq.length
).Now choose any such
A
andB
such thatmax(depth(A), depth(B))
is the minimum possible value.Return an
answer
array (of lengthseq.length
) that encodes such a choice ofA
andB
:answer[i] = 0
ifseq[i]
is part ofA
, elseanswer[i] = 1
. Note that even though multiple answers may exist, you may return any of them.Example 1:
Input: seq = "(()())"
Output: [0,1,1,1,1,0]Example 2:
Input: seq = "()(())()"
Output: [0,0,0,1,1,0,1,1]Constraints:
1 <= seq.size <= 10000
解题思路:方法很简单,就是嵌套的括号进行均分,使得A = B或者A+1 = B 即可。用a_count和b_count分别记录A与B未配对的左括号数量。然后遍历seq,如果seq[i]为左括号,判断a_count与b_count的大小:如果a_count <= b_count ,表示这个左括号划分到A中,a_count ++;否则划分到B,b_count++。 如果seq[i]是右括号,判断a_count与b_count的大小:如果a_count >= b_count ,表示这个右括号优先于A中的左括号匹配,a_count -- ;否则与B匹配,b_count --。
代码如下:
class Solution(object):
def maxDepthAfterSplit(self, seq):
"""
:type seq: str
:rtype: List[int]
"""
res = []
a_count = 0
b_count = 0 a_s = ''
b_s = ''
for i in seq:
if i == '(':
if a_count <= b_count:
res.append(0)
a_count += 1
a_s += i
else:
res.append(1)
b_count += 1
b_s += i elif i == ')':
if a_count >= b_count:
res.append(0)
a_count -= 1
a_s += i
else:
res.append(1)
b_count -= 1
b_s += i
#print a_s,b_s
return res
最新文章
- 关于Lucene 3.0升级到Lucene 4.x 备忘
- 【软件编程】乐易贵宾VIP教程 - JS改写+网页操作系列教程
- sell- 获取邮箱的后缀
- 【转】FFMPEG 库移植到 VC 需要的步骤
- Back to Back Order Process
- VS2010 远程调试
- Serializable 序列化为字符串 base64
- PHP MSSQL数据操作PDO API
- Hdu 2874 Connections between cities
- @property属性关键字
- Flex之HTML5视频播放解决方案
- HDU_1698 Just a Hook(线段树+lazy标记)
- 自动化测试辅助工具(Selenium IDE等)
- 题解:[JSOI2004]平衡点 / 吊打XXX
- pytorch学习: 构建网络模型的几种方法
- MySQL9:索引实战
- mysql存储过程变量的拼接
- debian安装nodejs
- depth: working copy\infinity\immediates\files\empty
- 分布式锁的两种实现方式(基于redis和基于zookeeper)
热门文章
- 【工具安装】VMware 安装教程
- Delphi Tokyo 10.2.3发布了
- linux防火墙iptables简单介绍
- 【Qt开发】Qt测试计算时间
- [DS+Algo] 004 栈、队列及其代码实现
- restful风格详解
- [多校联考2019(Round 4 T2)][51nod 1288]汽油补给(ST表+单调栈)
- [Codeforces 1214D]Treasure Island(dfs)
- MySQL explain,type分析(转)
- SCUT - 486 - 无向图上的点 - Dijkstra