![]() |
VOOZH | about |
Given string str of the type "3(ab)4(cd)", the task is to expand it to "abababcdcdcdcd" where integers are from the range [1, 9].
This problem was asked in ThoughtWorks interview held in October 2018.
Examples:
Input: str = "3(ab)4(cd)"
Output: abababcdcdcdcd
Input: str = "2(kl)3(ap)"
Output: klklapapap
Approach: We traverse through the string and wait for a numeric value, num to turn up at position i. As soon as it arrives, we check i + 1 for a '('. If it's present, then the program enters into a loop to extract whatever is within '(' and ')' and concatenate it to an empty string, temp. Later, another loop prints the generated string num number of times. Repeat these steps until the string finishes.
Below is the implementation of the approach:
abababcdcdcdcd
Time Complexity: O(N*N)
Auxiliary Space: O(1)
To enhance the efficiency of solutions for decoding strings with nested encodings across different programming languages, we can adopt a unified and optimal approach utilizing data structures and language-specific string manipulation capabilities. This optimized strategy can be applied broadly, irrespective of the programming language, by following these key principles:
Below is the implementation of above approach:
Below is the implementation of above approach:
abababcdcdcdcd
Time Complexity: O(n), where n is the length of the input string. The complexity arises from iterating through each character in the string and possibly multiplying substrings. The actual time complexity in practice is very close to linear because each character is effectively processed a fixed number of times due to the stack operations.
Auxilary Space: O(n), as in the worst case, the stack and the current_string combined may hold nearly an entire copy of the input string, especially in cases where the string is deeply nested or contains many repeated segments.