文章目录
- 算法题
算法题
1 三数之和 (注意去重的边界条件,过几天再刷几次)
2 长度最小的子数组 (代码随想录题目,滑动窗口)
3 用链表实现栈
package mainimport ("errors""fmt"
)// Node 定义链表节点
type Node struct {data intnext *Node
}// Stack 定义栈结构
type Stack struct {top *Node
}// NewStack 创建一个新的空栈
func NewStack() *Stack {return &Stack{nil}
}// Push 将元素压入栈顶
func (s *Stack) Push(data int) {s.top = &Node{data, s.top}
}// Pop 移除并返回栈顶元素
func (s *Stack) Pop() (int, error) {if s.top == nil {return 0, errors.New("stack is empty")}data := s.top.datas.top = s.top.nextreturn data, nil
}// Traverse 遍历栈中的元素
func (s *Stack) Traverse() {for current := s.top; current != nil; current = current.next {fmt.Print(current.data, " ")}fmt.Println()
}func main() {stack := NewStack()// 推送元素stack.Push(1)stack.Push(2)stack.Push(3)// 遍历栈stack.Traverse() // 输出: 3 2 1// 弹出元素data, err := stack.Pop()if err == nil {fmt.Println("Pop:", data) // 输出: Pop: 3}// 再次遍历栈stack.Traverse() // 输出: 2 1
}
4 基础计算器
//标题
//10以内正整数的加乘括号运算的求解
//
//题目描述
//9+((8*2+3)+1)*2=
func opsSort(ops string) int {switch ops {case "*":return 2case "+":return 1default:return 0}
}func calc(nums []int, ops []string) (nums1 []int, ops1 []string) {right, left := nums[len(nums)-1], nums[len(nums)-2]nums = nums[:len(nums)-2]op := ops[len(ops)-1]ops = ops[:len(ops)-1]switch op {case "+":nums = append(nums, left+right)case "*":nums = append(nums, left*right)}return nums, ops
}func MathResult(raw string) int {paramStack, opsStack := make([]int, 0), make([]string, 0)for _, s := range raw {str := string(s)n, err := strconv.Atoi(str)if err == nil {paramStack = append(paramStack, n)} else {switch string(s) {case "(":opsStack = append(opsStack, str)case ")":for opsStack[len(opsStack)-1] != "(" {paramStack, opsStack = calc(paramStack, opsStack)}opsStack = opsStack[:len(opsStack)-1]case "+", "*":for len(opsStack) > 0 && opsSort(str) <= opsSort(opsStack[len(opsStack)-1]) {paramStack, opsStack = calc(paramStack, opsStack)}opsStack = append(opsStack, str)}}}for len(opsStack) > 0 {paramStack, opsStack = calc(paramStack, opsStack)}return paramStack[0]
}func main() {var a stringfmt.Scan(&a)// a := "8*2+3"// a := "9+((8*2+3)+1)*2"// a := "2*(3+4)"fmt.Println(MathResult(a))
}