diff --git a/src/stack/decode_string/__init__.py b/src/stack/decode_string/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/stack/decode_string/solution.py b/src/stack/decode_string/solution.py new file mode 100644 index 0000000..6ac71ff --- /dev/null +++ b/src/stack/decode_string/solution.py @@ -0,0 +1,20 @@ +class Solution: + def decodeString(self, s: str) -> str: + stack = [] + number = [] + + for char in s: + if char.isdigit(): + number.append(char) + elif char == '[': + stack.append("".join(number)) + number = [] + elif char == ']': + alphas = [] + while stack[-1].isalpha(): + alphas.append(stack.pop()) + stack.extend(reversed(alphas * int(stack.pop()))) + else: + stack.append(char) + + return "".join(stack) diff --git a/tests/test_decode_string.py b/tests/test_decode_string.py new file mode 100644 index 0000000..1fe9e85 --- /dev/null +++ b/tests/test_decode_string.py @@ -0,0 +1,17 @@ +import pytest +from src.stack.decode_string.solution import ( + Solution, +) + + +@pytest.mark.parametrize( + "s, expected", + [ + ("3[a]2[bc]", "aaabcbc"), + ("3[a2[c]]", "accaccacc"), + ("2[abc]3[cd]ef", "abcabccdcdcdef"), + ], +) +def test_decode_string(s, expected): + solution = Solution() + assert solution.decodeString(s) == expected