-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathdecodeString.go
More file actions
97 lines (75 loc) · 2.65 KB
/
decodeString.go
File metadata and controls
97 lines (75 loc) · 2.65 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/*
Challenge: decodeString
https://codefights.com/interview-practice/task/dYCH8sdnxGf5aGkez/description
Given an encoded string, return its corresponding decoded string.
The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is repeated exactly k times. Note: k is guaranteed to be a positive integer.
Note that your solution should have linear complexity because this is what you will be asked during an interview.
Example
For s = "4[ab]", the output should be
decodeString(s) = "abababab";
For s = "2[b3[a]]", the output should be
decodeString(s) = "baaabaaa";
For s = "z1[y]zzz2[abc]", the output should be
decodeString(s) = "zyzzzabcabc".
Input/Output
[time limit] 4000ms (go)
[input] string s
A string encoded as described above. It is guaranteed that:
the string consists only of digits, square brackets and lowercase English letters;
the square brackets form a regular bracket sequence;
all digits that appear in the string represent the number of times the content in the brackets that follow them repeats, i.e. k in the description above;
there are at most 20 pairs of square brackets in the given string.
Guaranteed constraints:
0 ≤ s.length ≤ 80.
[output] string
*/
func decodeString(s string) string {
if len(s) == 0 {
return ""
}
// start reading
// if chars add to result
// if num repeat sub result x times
// recurse remaining
// start reading right to left
res := ""
for z, r := range s {
if r >= 97 && r < 123 {
res = res + string(r)
} else if r >= 48 && r <= 57 {
// read until we hit bracket
numStr := ""
i := z
r = rune(s[i])
for r != '[' {
numStr += string(s[i])
i++
r = rune(s[i])
}
num, _ := strconv.Atoi(numStr)
// find closing bracket
closeIndex := 0
lcount := 0
for n, r := range s[i:] {
if r == '[' {
lcount++
} else if r == ']' {
lcount--
}
if lcount == 0 {
closeIndex = i + n
break
}
}
recurseString := decodeString(s[i+1:closeIndex])
// append the result x times
for j := 0; j < num; j++ {
res = res + recurseString
}
// recurse on anything right of the closing bracket
res = res + decodeString(s[closeIndex+1:])
break
}
}
return res
}