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
| package main
import ( "fmt" "strings" )
func decodeString(s string) string { type stackElem struct { num int str string } stack := []stackElem{} currentNum := 0 currentStr := ""
for _, char := range s { switch { case char >= '0' && char <= '9': currentNum = currentNum*10 + int(char - '0') case char >= 'a' && char <= 'z' || char >= 'A' && char <= 'Z': currentStr += string(char) case char == '[': stack = append(stack, stackElem{currentNum, currentStr}) currentNum = 0 currentStr = "" case char == ']': top := stack[len(stack)-1] stack = stack[:len(stack)-1] currentStr = top.str + strings.Repeat(currentStr, top.num) } } return currentStr }
func main() { testCases := []struct { input string expected string }{ {"3[a]2[bc]", "aaabcbc"}, {"3[a2[c]]", "accaccacc"}, {"2[abc]3[cd]ef", "abcabccdcdcdef"}, {"abc3[cd]xyz", "abccdcdcdxyz"}, }
for i, tc := range testCases { result := decodeString(tc.input) fmt.Printf("Test Case %d, Input: %q\n", i+1, tc.input)
if result == tc.expected { fmt.Printf("Test Case %d, Output: %q, PASS\n", i+1, result) } else { fmt.Printf("Test Case %d, Output: %q, FAIL (Expected: %q)\n", i+1, result, tc.expected) } } }
|