学习目标

  • 了解算法题的解题思路
  • 栈的特点
  • 栈的应用

    题目:删除最外层括号

    本题来源

  • Leetcode 1021 https://leetcode-cn.com/problems/remove-outermost-parentheses/

    给出一个非空有效字符串S,考虑将其进行原语化分解。 使得:S=P_1+P_2+…+P_k,其中P_i是有效括号字符串原语。 对S进行原语化分解,删除分解中每个原语字符串的最外层括号,返回S。 ➢ 有效括号字符串:例如:”( )”,”( ( ) ) ( )” 和 “( ( ) ( ( ) ) )” ➢ 原语:如果有效字符串S非空,且不能将其拆分为 S =A+B,我们称其为原语(primitive), 其中A和B都是非空有效括号字符串

image.png

理解题意

题目基本信息
• 有效括号字符串:括号必然成对出现
• 给定字符串 S 非空,但返回结果可能为空
• 原语化分解只需要进行一级
• 返回删除每个原语的最外层括号后的字符串
附加信息
• S.length <= 10000
• S[i] 为 “(“ 或 “)”

解法一:暴力解法

  • 先分解成字符串原语
  • 再删除每部分最外层括号
  • 返回各部分合并后的结果

分析

  1. 定义容器存储原语子串
    new ArrayList();
  2. 定义左括号、右括号计数器:
    int left = 0, right = 0;
  3. 遍历字符串,读取到括号时对应计数器自增
  4. 检查是否到达原语结尾,截取原语子串并添加
    到容器中
  5. 遍历容器,删除最外层括号后合并成新串
    1. var removeOuterParentheses = function (s) {
    2. var strArr = s.split('') //分解字符串数组
    3. var left = 0, right = 0, str = ''
    4. var resArr=[] //存储整个有效括号组
    5. strArr.forEach((item, index, arr) => {
    6. if (item === '(') {
    7. left++
    8. } else {
    9. right++
    10. }
    11. str += item
    12. if (left === right) {
    13. // 表示已经遍历到一个元祖字符串了
    14. resArr.push(str)
    15. str = ''
    16. }
    17. })
    18. // 遍历resArr数组,得到result结果
    19. var result = resArr.reduce((prev,next)=>{
    20. prev += next.slice(1,next.length-1) //切割
    21. return prev
    22. },'')
    23. return result
    24. };

优化解法一

  • 对原字符串进行原语识别
  • 获取不包含最外层括号的子串
  • 将各部分拼接返回

分析

  1. 定义容器存储删除外层括号后的原语子串
    new StringBuilder();
  2. 定义左括号、右括号计数器:
    int left = 0, right = 0;
  3. 遍历字符串,读取到括号时对应计数器自增
  4. 检查是否到达原语结尾,截取不包含最外层的
    原语子串并拼接到容器中
    1. var removeOuterParentheses = function (s) {
    2. var strArr = s.split('') //分解字符串数组
    3. var count = 0, str = '', result = ''
    4. strArr.forEach((item) => {
    5. if (item === '(') {
    6. count++
    7. } else {
    8. count--
    9. }
    10. str += item
    11. if (count === 0) {
    12. // 表示已经遍历到一个元祖字符串了
    13. result += str.slice(1, str.length - 1)
    14. str = ''
    15. }
    16. })
    17. // 遍历resArr数组,得到result结果
    18. return result
    19. };

思考更优解

  1. 剔除无效代码或优化空间消耗
    • 只需要一个计数器:”(“自增,”)”自减
    • 如果字符串数据只是两两配对怎么处理?
    • 有没有一种支持后进先出的数据结构?
  2. 寻找更好的算法思维
    • 借鉴其它算法

image.png

关键知识点 : 栈

  • 限定仅在表尾进行插入和删除操作的线性表
  • 栈顶(Top):操作数据的一端,即表尾
  • 栈底(Bottom):线性表的另一端,即表头
  • 特点:LIFO(Last In First Out),后进先出
  • 基本操作
    • 进栈:push(),在栈顶插入元素,入栈、压栈
    • 出栈:pop(),从栈顶删除数据
    • 判断空:isEmpty现方法

image.png

最优解:栈解法

  1. 直接用数组取代栈
    创建数组、栈顶索引,使用数组操作入栈和出栈
  2. 将原字符串转为数组进行遍历
    char[] s = S.toCharArray();
  3. 去掉截取子串的操作,将原语字符直接拼接
    读取到左括号:此前有数据,当前必属原语
    读取到右括号:匹配后不为0,当前必属原语
    1. var removeOuterParentheses = function (s) {
    2. var strArr = s.split('') //分解字符串数组
    3. var result = '', stack = [],count = 0
    4. strArr.forEach(item => {
    5. if (item === '(') {
    6. if (stack.length >= 1) {
    7. result += item
    8. }
    9. count++
    10. stack.push(item)
    11. } else {
    12. if (stack.length > 1) {
    13. result += item
    14. }
    15. stack.pop()
    16. }
    17. })
    18. return result
    19. };
    1. var removeOuterParentheses = function (s) {
    2. let result = '',count = 0
    3. for (let i = 0; i < s.length; i++) {
    4. if(s[i] === '('){
    5. if(count > 0){
    6. result += s[i]
    7. }
    8. count++
    9. } else {
    10. if(count > 1){
    11. result += s[i]
    12. }
    13. count--
    14. }
    15. }
    16. return result
    17. };

延伸拓展

题目变形

  • (练习)删除最内层的括号
  • (练习)用链表实现一个栈(链栈))

延伸扩展

  • 逆波兰表达式求值:给定数字和运算符,根据规则计算出结果
  • 子程序调用:方法依次进栈,最后调用的最先结束

课后练习

  1. 最小栈(Leetcode 155/简单)
  2. 栈的压入、弹出序列(剑指 Offer 31/简单)
  3. 堆盘子(面试题 03.03/中等)
  4. 餐盘栈(Leetcode 1172/困难)

题目一 Leetcode155

155. 最小栈

暴力解法

  1. var MinStack = function () {
  2. this.index = -1
  3. this.elements = []
  4. };
  5. /**
  6. * @param {number} val
  7. * @return {void}
  8. */
  9. MinStack.prototype.push = function (val) {
  10. this.elements.push(val)
  11. this.index++
  12. };
  13. /**
  14. * @return {void}
  15. */
  16. MinStack.prototype.pop = function () {
  17. this.elements.pop()
  18. this.index--
  19. };
  20. /**
  21. * @return {number}
  22. */
  23. MinStack.prototype.top = function () {
  24. return this.elements[this.index]
  25. };
  26. /**
  27. * @return {number}
  28. */
  29. MinStack.prototype.getMin = function () {
  30. min = Math.min(...this.elements)
  31. return min
  32. };

image.png

尝试优化:

  • 使用min变量存储最低值
  • 在push的时候,对比替换最低值
  • 在pop的时候,如果去除的元素是最低值,则遍历栈 重新查询一个最低值 ```javascript var MinStack = function () { this.index = -1 this.elements = [] this.min = null };

/**

  • @param {number} val
  • @return {void} */ MinStack.prototype.push = function (val) { if(val < this.min || this.min == null ){

    1. this.min = val

    }

    this.elements.push(val) this.index++

};

/**

  • @return {void} */ MinStack.prototype.pop = function () { if (this.elements[this.index] == this.min) {
    1. this.elements.pop()
    2. this.index--
    3. this.min = Math.min(...this.elements)
    4. return
    } this.elements.pop() this.index—

};

/**

  • @return {number} */ MinStack.prototype.top = function () { return this.elements[this.index] };

/**

  • @return {number} */ MinStack.prototype.getMin = function () { // min = Math.min(…this.elements) return this.min };
  1. <a name="NDHHd"></a>
  2. ### ![image.png](https://cdn.nlark.com/yuque/0/2022/png/22738357/1662264366997-3b1e95d2-46db-44f7-9cb4-e5390a4084e6.png#clientId=u54c0ca3c-4a93-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=142&id=u6464d2f2&margin=%5Bobject%20Object%5D&name=image.png&originHeight=142&originWidth=444&originalType=binary&ratio=1&rotation=0&showTitle=false&size=15292&status=done&style=none&taskId=u8398a973-5737-4c5a-954b-6d79304146d&title=&width=444)
  3. <a name="c1DCc"></a>
  4. ### 尝试使用对象模仿栈来实现
  5. ```javascript
  6. MinStack.prototype.push = function (val) {
  7. if (val < this.min || this.min == null) {
  8. this.min = val
  9. }
  10. this.index++
  11. this[this.index] = val
  12. };
  13. /**
  14. * @return {void}
  15. */
  16. MinStack.prototype.pop = function () {
  17. if (this[this.index] == this.min) {
  18. this[this.index] = null
  19. this.index--
  20. // 重新找出最大值
  21. this.min = this[this.index]
  22. for (let i = 0; i <= this.index - 1; i++) {
  23. if (this[i] < this.min || this.min == null) {
  24. this.min = this[i]
  25. }
  26. }
  27. return
  28. }
  29. this[this.index] = null
  30. this.index--
  31. };
  32. /**
  33. * @return {number}
  34. */
  35. MinStack.prototype.top = function () {
  36. return this[this.index]
  37. };
  38. /**
  39. * @return {number}
  40. */
  41. MinStack.prototype.getMin = function () {
  42. return this.min
  43. };

还不错的成绩
image.png

题目二 剑指Offer 31

剑指 Offer 31. 栈的压入、弹出序列

  1. var validateStackSequences = function (pushed, popped) {
  2. let l = pushed.length
  3. let stack = []
  4. let j = 0
  5. for(let i= 0; i < l; i++) {
  6. stack.push(pushed[i])
  7. while(stack.length && stack[stack.length - 1] == popped[j]) {
  8. stack.pop();
  9. j++;
  10. }
  11. }
  12. return !stack.length
  13. };

题目三 面试题03.03

面试题 03.03. 堆盘子
难,没有更好的思路

  1. /**
  2. * @param {number} cap
  3. */
  4. var StackOfPlates = function (cap) {
  5. this.cap = cap // 栈的高度限制
  6. this.stacks = [] //栈的总和
  7. this.index = -1
  8. };
  9. /**
  10. * @param {number} val
  11. * @return {void}
  12. */
  13. StackOfPlates.prototype.push = function (val) {
  14. return this.popAt(this.stacks.length - 1)
  15. // if (this.cap == 0) {
  16. // return
  17. // }
  18. // // 1.找出自己应该加在哪个索引
  19. // if (this.index == -1) { //处理数组为空的情况
  20. // this.index++
  21. // this.stacks[this.index] = [val]
  22. // return
  23. // }
  24. // if (this.stacks[this.index].length == this.cap) { //处理元素满了的情况
  25. // this.index++
  26. // this.stacks[this.index] = []
  27. // }
  28. // // 2.加入元素
  29. // this.stacks[this.index].push(val)
  30. // return
  31. };
  32. /**
  33. * @return {number}
  34. */
  35. StackOfPlates.prototype.pop = function () {
  36. // 前置判断
  37. if (this.index == -1) { return -1 }
  38. // 1.删减元素
  39. let result = this.stacks[this.index].pop()
  40. // 3.如果这个栈已经没有元素了,我们就删除它
  41. if (this.stacks[this.index] == '') {
  42. this.stacks.pop()
  43. this.index--
  44. }
  45. // 5.返回结果
  46. return result
  47. };
  48. /**
  49. * @param {number} index
  50. * @return {number}
  51. */
  52. StackOfPlates.prototype.popAt = function (index) {
  53. // 前置判断
  54. if (this.index == -1 || index > this.stacks.length - 1) {
  55. return -1
  56. }
  57. // 2.删减元素
  58. let result = this.stacks[index].pop()
  59. // 3.如果删减后,栈为空,删除这个栈
  60. if (this.stacks[index] == '') {
  61. this.stacks = [...this.stacks.slice(0, index), ...this.stacks.slice(index + 1, this.stacks.length)]
  62. this.index--
  63. }
  64. // 返回结果
  65. return result
  66. };
  67. /**
  68. * Your StackOfPlates object will be instantiated and called as such:
  69. * var obj = new StackOfPlates(cap)
  70. * obj.push(val)
  71. * var param_2 = obj.pop()
  72. * var param_3 = obj.popAt(index)
  73. */

解法二

  1. /**
  2. * @param {number} cap
  3. */
  4. var StackOfPlates = function (cap) {
  5. this.cap = cap // 栈的高度限制
  6. this.stacks = [] //栈的总和
  7. };
  8. /**
  9. * @param {number} val
  10. * @return {void}
  11. */
  12. StackOfPlates.prototype.push = function (val) {
  13. if (this.cap == 0) {
  14. return
  15. }
  16. // 1.找出自己应该加在哪个索引
  17. if (this.stacks.length == 0 || this.stacks[this.stacks.length - 1].length == this.cap) { //处理数组为空的情况
  18. this.stacks[this.stacks.length] = [val]
  19. return
  20. }
  21. // 2.加入元素
  22. this.stacks[this.stacks.length - 1].push(val)
  23. return
  24. };
  25. /**
  26. * @return {number}
  27. */
  28. StackOfPlates.prototype.pop = function () {
  29. // 前置判断
  30. if (this.stacks.length == 0) { return -1 }
  31. // 1.删减元素
  32. let result = this.stacks[this.stacks.length - 1].pop()
  33. // 3.如果这个栈已经没有元素了,我们就删除它
  34. if (this.stacks[this.stacks.length - 1] == '') {
  35. this.stacks.pop()
  36. }
  37. // 5.返回结果
  38. return result
  39. };
  40. /**
  41. * @param {number} index
  42. * @return {number}
  43. */
  44. StackOfPlates.prototype.popAt = function (index) {
  45. // 前置判断
  46. if (this.stacks.length == 0 || index > this.stacks.length - 1) {
  47. return -1
  48. }
  49. // 2.删减元素
  50. let result = this.stacks[index].pop()
  51. // 3.如果删减后,栈为空,删除这个栈
  52. if (this.stacks[index] == '') {
  53. this.stacks = [...this.stacks.slice(0, index), ...this.stacks.slice(index + 1, this.stacks.length)]
  54. }
  55. // 返回结果
  56. return result
  57. };
  58. /**
  59. * Your StackOfPlates object will be instantiated and called as such:
  60. * var obj = new StackOfPlates(cap)
  61. * obj.push(val)
  62. * var param_2 = obj.pop()
  63. * var param_3 = obj.popAt(index)
  64. */