Expand the string according to the given conditions
Last Updated :
09 May, 2024
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:
C++
// C++ implementation of the approach
#include<bits/stdc++.h>
using namespace std;
// Function to expand and print the given string
void expandString(string strin)
{
string temp = "";
int j;
for (int i = 0; i < strin.length(); i++)
{
if (strin[i] >= 0)
{
// Subtract '0' to convert char to int
int num = strin[i] - '0';
if (strin[i + 1] == '(')
{
// Characters within brackets
for (j = i + 1; strin[j] != ')'; j++)
{
if ((strin[j] >= 'a' && strin[j] <= 'z') ||
(strin[j] >= 'A' && strin[j] <= 'Z'))
{
temp += strin[j];
}
}
// Expanding
for (int k = 1; k <= num; k++)
{
cout << (temp);
}
// Reset the variables
num = 0;
temp = "";
if (j < strin.length())
{
i = j;
}
}
}
}
}
// Driver code
int main()
{
string strin = "3(ab)4(cd)";
expandString(strin);
}
// This code is contributed by Surendra_Gangwar
Java
// Java implementation of the approach
public class GFG {
// Function to expand and print the given string
static void expandString(String strin)
{
String temp = "";
int j;
for (int i = 0; i < strin.length(); i++) {
if (strin.charAt(i) >= 0) {
// Subtract '0' to convert char to int
int num = strin.charAt(i) - '0';
if (strin.charAt(i + 1) == '(') {
// Characters within brackets
for (j = i + 1; strin.charAt(j) != ')'; j++) {
if ((strin.charAt(j) >= 'a'
&& strin.charAt(j) <= 'z')
|| (strin.charAt(j) >= 'A'
&& strin.charAt(j) <= 'Z')) {
temp += strin.charAt(j);
}
}
// Expanding
for (int k = 1; k <= num; k++) {
System.out.print(temp);
}
// Reset the variables
num = 0;
temp = "";
if (j < strin.length()) {
i = j;
}
}
}
}
}
// Driver code
public static void main(String args[])
{
String strin = "3(ab)4(cd)";
expandString(strin);
}
}
Python
# Python3 implementation of the approach
# Function to expand and print the given string
def expandString(strin):
temp = ""
j = 0
i = 0
while(i < len(strin)):
if (strin[i] >= "0"):
# Subtract '0' to convert char to int
num = ord(strin[i])-ord("0")
if (strin[i + 1] == '('):
# Characters within brackets
j = i + 1
while(strin[j] != ')'):
if ((strin[j] >= 'a' and strin[j] <= 'z') or \
(strin[j] >= 'A' and strin[j] <= 'Z')):
temp += strin[j]
j += 1
# Expanding
for k in range(1, num + 1):
print(temp,end="")
# Reset the variables
num = 0
temp = ""
if (j < len(strin)):
i = j
i += 1
# Driver code
strin = "3(ab)4(cd)"
expandString(strin)
# This code is contributed by shubhamsingh10
C#
// C# implementation of
// the above approach
using System;
class GFG{
// Function to expand and
// print the given string
static void expandString(string strin)
{
string temp = "";
int j;
for (int i = 0;
i < strin.Length; i++)
{
if (strin[i] >= 0)
{
// Subtract '0' to
// convert char to int
int num = strin[i] - '0';
if (strin[i + 1] == '(')
{
// Characters within brackets
for (j = i + 1;
strin[j] != ')'; j++)
{
if ((strin[j] >= 'a' &&
strin[j] <= 'z') ||
(strin[j] >= 'A' &&
strin[j] <= 'Z'))
{
temp += strin[j];
}
}
// Expanding
for (int k = 1; k <= num; k++)
{
Console.Write(temp);
}
// Reset the variables
num = 0;
temp = "";
if (j < strin.Length)
{
i = j;
}
}
}
}
}
// Driver code
public static void Main(String [] args)
{
string strin = "3(ab)4(cd)";
expandString(strin);
}
}
// This code is contributed by Chitranayal
Javascript
<script>
// Javascript implementation of the approach
// Function to expand and print the given string
function expandString(strin)
{
let temp = "";
let j;
for (let i = 0; i < strin.length; i++) {
if (strin[i].charCodeAt(0) >= 0) {
// Subtract '0' to convert char to int
let num = strin[i].charCodeAt(0) - '0'.charCodeAt(0);
if (strin[i+1] == '(') {
// Characters within brackets
for (j = i + 1; strin[j] != ')'; j++) {
if ((strin[j] >= 'a'
&& strin[j] <= 'z')
|| (strin[j] >= 'A'
&& strin[j] <= 'Z')) {
temp += strin[j];
}
}
// Expanding
for (let k = 1; k <= num; k++) {
document.write(temp);
}
// Reset the variables
num = 0;
temp = "";
if (j < strin.length) {
i = j;
}
}
}
}
}
// Driver code
let strin = "3(ab)4(cd)";
expandString(strin);
// This code is contributed by rag2127
</script>
Time Complexity: O(N*N)
Auxiliary Space: O(1)
Approach using Stack:
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:
- Use a stack to manage nested encodings. Push tuples or pairs onto the stack.
- As the input is parsed, construct numeric multipliers when digits are encountered.
- When a start marker like ( is encountered, push the current state onto the stack and reset your working string and multiplier. ), pop the stack to get the context (the string before this nested sequence and the multiplier).
- Repeat the current string segment as specified by the multiplier and concatenate it with the string retrieved from the stack.
- Once the entire string has been parsed, the current working string (stored in a variable like current_string) will hold the fully decoded string.
Below is the implementation of above approach:
C++
#include <cctype>
#include <iostream>
#include <stack>
using namespace std;
string decodeString(string s)
{
stack<pair<string, int> > st;
int num = 0;
string current_string = "";
for (char c : s) {
if (isdigit(c)) {
num = num * 10
+ (c
- '0'); // Build the multiplier number
}
else if (c == '(') {
// Push the current number and string onto the
// stack
st.push({ current_string, num });
current_string = ""; // Reset current string
num = 0; // Reset the number
}
else if (c == ')') {
// Pop the string and multiplier from the stack
string last_string = st.top().first;
int multiplier = st.top().second;
st.pop();
for (int i = 0; i < multiplier; ++i) {
last_string += current_string;
}
current_string = last_string;
}
else {
current_string += c; // Add the current
// character to the string
}
}
return current_string;
}
// Example usage
int main()
{
cout << decodeString("3(ab)4(cd)") << endl;
return 0;
}
Java
import java.util.Stack;
public class Main {
static String decodeString(String s)
{
Stack<String> stack = new Stack<>();
StringBuilder currentString = new StringBuilder();
int num = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (Character.isDigit(c)) {
num = num * 10
+ Character.getNumericValue(c);
}
else if (c == '(') {
stack.push(currentString.toString());
stack.push(String.valueOf(num));
currentString.setLength(
0); // Reset current string
num = 0; // Reset the number
}
else if (c == ')') {
int multiplier
= Integer.parseInt(stack.pop());
String lastString = stack.pop();
StringBuilder repeatedString
= new StringBuilder();
for (int j = 0; j < multiplier; j++) {
repeatedString.append(currentString);
}
currentString = new StringBuilder(
lastString + repeatedString);
}
else {
currentString.append(c);
}
}
return currentString.toString();
}
// Example usage
public static void main(String[] args)
{
System.out.println(decodeString("3(ab)4(cd)"));
}
}
Python
def decodeString(s):
stack = []
num = 0
current_string = ""
for char in s:
if char.isdigit():
num = num * 10 + int(char) # Build the multiplier number
elif char == '(':
# Push the current number and string onto the stack
stack.append((current_string, num))
current_string = "" # Reset current string
num = 0 # Reset the number
elif char == ')':
# Pop the string and multiplier from the stack
last_string, multiplier = stack.pop()
current_string = last_string + (current_string * multiplier)
else:
current_string += char # Add the current character to the string
return current_string
# Example usage
print(decodeString("3(ab)4(cd)"))
JavaScript
function decodeString(s) {
let stack = [];
let num = 0;
let currentString = "";
for (let i = 0; i < s.length; i++) {
let char = s[i];
if (!isNaN(char)) {
num = num * 10 + parseInt(char); // Build the multiplier number
} else if (char === '(') {
// Push the current number and string onto the stack
stack.push([currentString, num]);
currentString = ""; // Reset current string
num = 0; // Reset the number
} else if (char === ')') {
// Pop the string and multiplier from the stack
let [lastString, multiplier] = stack.pop();
currentString = lastString + currentString.repeat(multiplier);
} else {
currentString += char; // Add the current character to the string
}
}
return currentString;
}
// Example usage
console.log(decodeString("3(ab)4(cd)"));
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.
Share your thoughts in the comments
Please Login to comment...