The problem
Think about the next growth:
// as a result of "ab" repeats 3 occasions
clear up("3(ab)") == "ababab"
// as a result of "a3(b)" == "abbb", which repeats twice.
clear up("2(a3(b))") == "abbbabbb"
Given a string, return the growth of that string.
Enter will include solely lowercase letters and numbers (1 to 9) in legitimate parenthesis. There can be no letters or numbers after the final closing parenthesis.
The answer in Java code
Choice 1:
class Resolution{
public static String clear up(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;
}
}
Choice 2:
class Resolution{
public static String clear up(String s){
String reply = "";
int multiplier = 1;
for (int i = 0; i< s.size(); i++) {
char image = s.charAt(i);
if (Character.isLetter(image)) {
reply += image;
} else if (Character.isDigit(image)) {
multiplier = Character.getNumericValue(image);
} else if (image == '(') {
return reply + clear up(s.substring(i + 1)).repeat(multiplier);
}
}
return reply;
}
}
Choice 3:
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Sample;
class Resolution{
public static String clear up(String s) {
Sample sample = Sample.compile("((d+)?(([a-z]+)))");
for (;;) {
Matcher matcher = sample.matcher(s);
if (!matcher.discover()) {
break;
}
String goal = matcher.group(1);
int repeat = matcher.group(2) == null ? 1 : Integer.parseInt(matcher.group(2));
String worth = matcher.group(3);
StringBuilder builder = new StringBuilder();
for (int ii = 0; ii < repeat; ii++) {
builder.append(worth);
}
s = s.substitute(goal, builder.toString());
}
return s;
}
}
Take a look at instances to validate our resolution
import org.junit.Take a look at;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;
public class SolutionTest{
@Take a look at
public void basicTests(){
assertEquals("ababab",Resolution.clear up("3(ab)"));
assertEquals("abbbabbb",Resolution.clear up("2(a3(b))"));
assertEquals("bccbccbcc",Resolution.clear up("3(b(2(c)))"));
assertEquals("kabaccbaccbacc",Resolution.clear up("ok(a3(b(a2(c))))"));
}
}