Given a string and a non-negative int n, we'll say that the front of the string is the first 3 chars, or whatever is there if the string is less than length 3. Return n copies of the front:
frontTimes("Chocolate", 2) → "ChoCho" frontTimes("Chocolate", 3) → "ChoChoCho" frontTimes("Abc", 3) → "AbcAbcAbc" frontTimes("X", 3) → "XXX"
I've solved above problem using following code but I'm using a new StringBuilder
to store intermediate string result. Does it really needed can I optimize and remove the for
loop in the else
?
public String frontTimes(String str, int n) {
StringBuilder sb = new StringBuilder(str);
StringBuilder newsb = new StringBuilder();
if(sb.length() >= 3)
{
for(int i = 0; i < n; i++)
{
newsb.append(sb.substring(0,3));
}
return newsb.toString();
}
else
{
for(int i = 0; i < n; i++)
{
newsb.append(sb.toString());
}
return newsb.toString();
}
}