Given a string S of '(' and ')' parentheses, we add the minimum number of parentheses ( '(' or ')', and in any positions ) so that the resulting parentheses string is valid.

Formally, a parentheses string is valid if and only if:

  • It is the empty string, or
  • It can be written as AB (A concatenated with B), where A and B are valid strings, or
  • It can be written as (A), where A is a valid string.

Given a parentheses string, return the minimum number of parentheses we must add to make the resulting string valid.

Example 1:

Input: "())"
Output: 1

Example 2:

Input: "((("
Output: 3

Example 3:

Input: "()"
Output: 0

Example 4:

Input: "()))(("
Output: 4

Note:

  1. S.length <= 1000
  2. S only consists of '(' and ')' characters.

Approach #1: C++.[stack]

class Solution {
public:
int minAddToMakeValid(string S) {
int len = S.length();
if (len == 0) return 0;
stack<char> myStack;
myStack.push(S[0]); for (int i = 1; i < len; ++i) {
if (myStack.empty()) myStack.push(S[i]);
else if (myStack.top() == '(' && S[i] == ')') myStack.pop();
else myStack.push(S[i]);
} return myStack.size();
}
};

  

最新文章

  1. html5中canvas的使用 获取鼠标点击页面上某点的RGB
  2. 【PHP&amp;&amp;mysqli】
  3. C++中使用函数指针 【瓦特芯笔记】
  4. GUI之CCControlExtension
  5. PowerDesigner创建物理模型
  6. C#(.Net)知识点记录
  7. Masonry适配的简单使用
  8. 使用Spring MVC构建REST风格WEB应用
  9. 解决Ubuntu SMPlayer播放视频无声音问题
  10. JS弹出下载对话框以及实现常见文件类型的下载
  11. python之log
  12. div变成输入框
  13. JavaScript几种常见的继承方法
  14. 将NULL值转化为“”
  15. 【HNOI2016】树
  16. HDU 1052(田忌赛马 贪心)
  17. SPI、I2C、UART三种串行总线协议的区别
  18. 初探 opencv-python
  19. IE6,IE7浏览器下 margin 无效的解决方法
  20. HDU 2161 Primes (素数筛选法)

热门文章

  1. 【原】Coursera—Andrew Ng机器学习—课程笔记 Lecture 14—Dimensionality Reduction 降维
  2. 前面部分(WCF全面解析1)
  3. zfs mount
  4. 在SharePoint解决方案中使用JavaScript (2) – 模块化
  5. vuejs 2.0 键盘事件
  6. 相机IMU融合四部曲(三):MSF详细解读与使用
  7. SQLSERVER Tempdb的作用及优化
  8. 处理事件冒泡,阻止默认事件工具类,兼容IE
  9. 【解决】SOUI向导生成项目(VC2013以上版本编译时)无法运行XP解决
  10. hibernate方言