Loading... 这道题需要注意的是k可能不止一位数,所以需要按照下面的规则进行: - 读取到 [ ,把当前的读取到的字符串和 repeat 值分别存储到一个栈。 - 每次读到 a-z 的字符直接拼接到当前字符串即可 - 读取到数字,累加 repeat 值 - 读取到 ],则需要取出栈内数字和栈内字符串,栈内数字用于把当前字符串重复 k 次,栈内字符串用于拼接在当前字符串的前边作为前缀,这样一套整体的流程下来即可符合题意。 ```go func decodeString(s string) string { curStr := "" cntStack := []int{} strStack := []string{} curNum := 0 for i := range s { if s[i] >= '0' && s[i] <= '9' { curNum *= 10 curNum += int(s[i]-'0') continue } if s[i] == '[' { cntStack = append(cntStack, curNum) strStack = append(strStack, curStr) curStr = "" curNum = 0 continue } if s[i] == ']' { cnt := cntStack[len(cntStack)-1] cntStack = cntStack[:len(cntStack)-1] prev := strStack[len(strStack)-1] strStack = strStack[:len(strStack)-1] curStr = prev + strings.Repeat(curStr, cnt) } if s[i] >= 'a' && s[i] <= 'z' { curStr += string(s[i]) } } return curStr } ``` Last modification:July 21, 2025 © Allow specification reprint Support Appreciate the author AliPayWeChat Like 如果觉得我的文章对你有用,请随意赞赏