代码随想录算法训练营第10天 | lc20、lc1047、lc150

发布时间 2023-12-10 03:12:51作者: geJoyo

(本合集全部为Go语言实现)

相关文章链接:20题解 1047题解 150题解
相关视频链接:

Leetcode20

状态:秒了
实现过程中的难点:经典的栈应用

从题解中学到的一个写法

func isValid(s string) bool {
  if (len(s) & 1) == 1 {
    return false
  }
  stack := make([]rune, 0)
  for _, c := range s {
    if c == '(' {
      stack = append(stack, ')')
    } else if c == '[' { 
      stack = append(stack, ']')
    } else if c == '{' {
      stack = append(stack, '}')
    } else if len(stack) == 0 || stack[len(stack) - 1] != c {
      return false
    } else {
      stack = stack[:len(stack) - 1]
    }
  }
  return len(stack) == 0
}

Leetcode1047

状态:秒了
实现过程中的难点:和括号匹配差不多的思路

个人写法

func removeDuplicates(s string) string {
  res := make([]rune, 0)
  for _, c := range s {
    if len(res) > 0 && res[len(res) - 1] == c {
      res = res[:len(res) - 1]
    } else {
      res = append(res, c)
    }
  }
  return string(res)
}

Leetcode150

状态:基本是秒了
实现过程中的难点:知道逆波兰式的求解思路就好写了

个人写法

import "strconv"

func evalRPN(tokens []string) int {
  var operand []int
  for _, item := range tokens {
    curLen := len(operand)
    var res int
    if item == "+" {
      res = operand[curLen - 2] + operand[curLen - 1]
    } else if item == "-" {
      res = operand[curLen - 2] - operand[curLen - 1]
    } else if item == "*" {
      res = operand[curLen - 2] * operand[curLen - 1]
    } else if item == "/" {
      res = operand[curLen - 2] / operand[curLen - 1]
    } else {
      if num, err := strconv.Atoi(item); err == nil {
        operand = append(operand, num)
      }
      continue
    }
    operand = operand[:curLen - 1]
    operand[curLen - 2] = res
  }
  return operand[0]
}

今日收获

  • 复习了一下go切片实现栈

学习时长:1.5小时左右