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


题目地址:https://leetcode.com/problems/remove-outermost-parentheses/

题目描述

A valid parentheses string is either empty (""), "(" + A + ")", or A + B, where A and B are valid parentheses strings, and + represents string concatenation. For example, "", "()", "(())()", and "(()(()))" are all valid parentheses strings.

A valid parentheses string S is primitive if it is nonempty, and there does not exist a way to split it into S = A+B, with A and B nonempty valid parentheses strings.

Given a valid parentheses string S, consider its primitive decomposition: S = P_1 + P_2 + ... + P_k, where P_i are primitive valid parentheses strings.

Return S after removing the outermost parentheses of every primitive string in the primitive decomposition of S.

Example 1:

Input: "(()())(())"
Output: "()()()"
Explanation:
The input string is "(()())(())", with primitive decomposition "(()())" + "(())".
After removing outer parentheses of each part, this is "()()" + "()" = "()()()".

Example 2:

Input: "(()())(())(()(()))"
Output: "()()()()(())"
Explanation:
The input string is "(()())(())(()(()))", with primitive decomposition "(()())" + "(())" + "(()(()))".
After removing outer parentheses of each part, this is "()()" + "()" + "()(())" = "()()()()(())".

Example 3:

Input: "()()"
Output: ""
Explanation:
The input string is "()()", with primitive decomposition "()" + "()".
After removing outer parentheses of each part, this is "" + "" = "".

Note:

  1. S.length <= 10000
  2. S[i] is “(” or “)”
  3. S is a valid parentheses string

题目大意

找出字符串中每对括号匹配的结果去除最外层的()之后的结果之和。

解题方法

遍历

看到括号匹配,大家一般都想到用一个栈,其实不用栈也可以。

我们只需要一个变量count保存左括号数-右括号数即可。即遇到左括号则自增1,遇到右括号则自减1.当count为0的时候,说明在这一段中左括号和右括号相等,是个完美匹配的括号串了。

我们使用一个变量previ保存的是上一次括号完全匹配之后,下一个括号匹配开始位置。由于这个题需要让我们把最外层的括号去掉,所以,当count==0的时候,我们把结果增加的是[previ + 1, i),左闭右开区间。

Python代码如下:

class Solution(object):
def removeOuterParentheses(self, S):
"""
:type S: str
:rtype: str
"""
previ = 0
res = ""
count = 0
for i, s in enumerate(S):
if s == '(':
count += 1
else:
count -= 1
if count == 0:
res += S[previ + 1: i]
previ = i + 1
return res

日期

2019 年 4 月 7 日 —— 周赛bug了3次。。

最新文章

  1. MySql: 忘记root密码
  2. UISearchController的使用
  3. 玩转html5&lt;canvas&gt;画图
  4. tttt
  5. struts2 的struts.xml配置详解
  6. &lt;转载&gt;CSS解决图片过大撑破DIV的方法
  7. redis权限认证(设置密码)的方法
  8. java方法:flush()
  9. 3分钟带你了解PowerShell发展历程——PowerShell各版本资料整理
  10. FastCGI
  11. HTML表格布局
  12. ACM山东工商 Contest - 软件171-2 第1次测验
  13. Spark Standalone 提交模式
  14. POJ 2240 Arbitrage (Bellman Ford判正环)
  15. hnctf安恒--蜘蛛侠呀
  16. day22 面向对象基础
  17. JS创建类的方法--简单易懂有实例
  18. kubeadm 线上集群部署(二) K8S Master集群安装以及工作节点的部署
  19. 配置Kafka集群和zookeeper集群
  20. oracle相关链接

热门文章

  1. 【蛋白质基因组】Proteogenomics方法介绍及分析思路
  2. android 点击图片从Fragment跳转到activity
  3. 4G网络 LTE、 FDD 和TD网络格式区别
  4. 完美png图片添加水印类
  5. C++ STL算法之:copy
  6. C++类成员初始化列表的构造顺序
  7. 学习java 7.9
  8. 【XSS】再谈CSP内容安全策略
  9. 双向循环链表模板类(C++)
  10. Maven pom.xml报错解决