394. 字符串解码

目录

394. 字符串解码

mid

image-20220816115637705

辅助栈

image-20220816120055905
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import "strconv"

type node struct {
	prevRes  string
	curMulti int
}

func decodeString(s string) string {
	stack := make([]node, 0)
	multi, tmpStr := 0, ""
	for i := 0; i < len(s); i++ {
		if '0' <= s[i] && s[i] <= '9' {
			// 累计数字
			num, _ := strconv.Atoi(string(s[i]))
			multi = multi*10 + num
		} else if s[i] == '[' {
			// 将之前的结果和这次的重复个数入栈
			stack = append(stack, node{prevRes: tmpStr, curMulti: multi})
			// 清空
			multi, tmpStr = 0, ""
		} else if s[i] == ']' {
			// 出栈 结算
			curNode := stack[len(stack)-1]
			stack = stack[:len(stack)-1]
			prevRes := curNode.prevRes
			for j := 0; j < curNode.curMulti; j++ {
				prevRes += tmpStr
			}
			tmpStr = prevRes
		} else {
			// 字母
			tmpStr += string(s[i])
		}
	}
	return tmpStr
}