-
Notifications
You must be signed in to change notification settings - Fork 1
/
decode-string.go
64 lines (46 loc) · 1.25 KB
/
decode-string.go
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package algorithms
import (
"github.com/goldennovember/leetcode-go/gods"
"strconv"
"strings"
)
type Stack = gods.Stack
func decodeString(s string) string {
stack := Stack{}
// Create a string to store the result
ans := ""
// Iterate through the string
for _, c := range s {
// If the character is a closing bracket
if c == ']' {
// Create a temp string to store the string in the brackets
str := ""
// Pop the stack until we see a opening bracket
for stack.Peek() != "[" {
str = stack.Pop().(string) + str
}
// Pop the opening bracket
stack.Pop()
// Create a string to store the number
// We can just not pop one more element for the number
// Because we can have a number with more than one digit like 100
num := ""
// Pop the stack until we see a non-number
for stack.Size() > 0 && stack.Peek().(string) >= "0" && stack.Peek().(string) <= "9" {
num = stack.Pop().(string) + num
}
// Convert the number to an integer
n, _ := strconv.Atoi(num)
// Repeat the string n times
repeat := strings.Repeat(str, n)
// Push the string back to the stack
stack.Push(repeat)
} else {
stack.Push(string(c))
}
}
for stack.Size() > 0 {
ans = stack.Pop().(string) + ans
}
return ans
}