Software Engineering

# Simple string expansion in Java

## The challenge#

Consider the following expansion:

``````// because "ab" repeats 3 times
solve("3(ab)") == "ababab"

// because "a3(b)" == "abbb", which repeats twice.
solve("2(a3(b))") == "abbbabbb"
``````

Given a string, return the expansion of that string.

Input will consist of only lowercase letters and numbers (1 to 9) in valid parenthesis. There will be no letters or numbers after the last closing parenthesis.

## The solution in Java code#

Option 1:

``````class Solution{
public static String solve(String s){
String new_s = "";
for(char ch : new StringBuilder(s).reverse().toString().toCharArray()) {
if(Character.isDigit(ch)) new_s = new_s.repeat(Integer.parseInt(ch + ""));
if(Character.isLetter(ch)) new_s = ch + new_s;
}
return new_s;
}
}
``````

Option 2:

``````class Solution{
public static String solve(String s){
int multiplier = 1;

for (int i = 0; i< s.length(); i++) {
char symbol = s.charAt(i);
if (Character.isLetter(symbol)) {
} else if (Character.isDigit(symbol)) {
multiplier = Character.getNumericValue(symbol);
} else if (symbol == '(') {
return answer + solve(s.substring(i + 1)).repeat(multiplier);
}
}
}
}
``````

Option 3:

``````import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class Solution{
public static String solve(String s) {
Pattern pattern = Pattern.compile("((\\d+)?\\(([a-z]+)\\))");

for (;;) {
Matcher matcher = pattern.matcher(s);
if (!matcher.find()) {
break;
}

String target = matcher.group(1);
int repeat = matcher.group(2) == null ? 1 : Integer.parseInt(matcher.group(2));
String value = matcher.group(3);

StringBuilder builder = new StringBuilder();

for (int ii = 0; ii < repeat; ii++) {
builder.append(value);
}

s = s.replace(target, builder.toString());
}

return s;
}
}
``````

## Test cases to validate our solution#

``````import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;

public class SolutionTest{
@Test
public void basicTests(){
assertEquals("ababab",Solution.solve("3(ab)"));
assertEquals("abbbabbb",Solution.solve("2(a3(b))"));
assertEquals("bccbccbcc",Solution.solve("3(b(2(c)))"));
assertEquals("kabaccbaccbacc",Solution.solve("k(a3(b(a2(c))))"));
}
}
``````