majianyu
2/20/2019 - 9:15 AM

682 棒球比赛

使用一个栈实现,根据 case 到不同的值进行对应操作

func calPoints(ops []string) int {
	st := &Stack{}
	for _, s := range ops {
		switch s {
		case "C":
			st.Pop()
		case "D":
			st.Push(st.Peek().(int) * 2)
		case "+":
			last, _ := st.Pop()
			n := last.(int) + st.Peek().(int)
			st.Push(last)
			st.Push(n)
		default:
			i, err := strconv.Atoi(s)
			if err != nil {
				panic(err)
			}
			st.Push(i)
		}
		fmt.Println(s, st)
	}
	sum := 0
	for {
		v, ok := st.Pop()
		if !ok {
			break
		}
		sum += v.(int)
	}
	return sum
}
type Stack struct {
	data []interface{}
}

func (this *Stack) Push(i interface{}) {
	this.data = append([]interface{}{i}, this.data...)
}
func (this *Stack) Peek() interface{} {
	return this.data[0]
}
func (this *Stack) Pop() (interface{}, bool) {
	if len(this.data) == 0 {
		return nil, false
	}
	i := this.Peek()
	this.data = this.data[1:]
	return i, true
}