I don't know this question is from your real work or is homework/ interview algorithm question.
The straightforward solution would be calculating the index of original string, inserting the new string to that position. Do this n times.
I just write an idea, not sure if it is ok: say we want to do insert 100(n) times
- first we take the string two, the
Monkey
- build two strings, one is
"Mon"
repeated 99 times (n-1), and the other one is "key"
, also repeat 99 times
- find out the insertion index of string ONE, say
i
- insert this string to
i
position: 99Mons + String TWO("Monkey") + 99keys
I am not sure if this is a good way to go...
Did a small test:
I am curious about the performance of my solution, so I did a small performance test, with the straightforward solution from @Ame Burmeister.
In my test:
- Tests are done with
Junit Test class
StopWatch
is from guava
warming up
4 times before measuring elapsed time, to avoid Jit
- the two methods give same output (with smaller n), both are correctly implemented.
- Both tested with
100000
Insertions
The straightforward solution (Basically just copy from @Ame's answer)
@Test
public void insertWithBuilder() {
final int n = 100000;
final String one = "MonkeyPony";
final String two = "Monkey";
final Stopwatch sw = new Stopwatch();
int x = 1;
for (; x <= 5; x++) {// loop 4 times (warming up) to avoid JIT
if (x == 5) {
sw.start();
}
final StringBuilder builder = new StringBuilder(one);
System.out.println("warming up times:" + x);
for (int i = 0; i < n; ++i) {
builder.insert(builder.length() / 2, two);
}
if (x == 5) {
sw.stop();
// System.out.println("builder:" + builder.toString());
}
}
System.out.println("SBuilder:" + sw.elapsedTime(TimeUnit.MILLISECONDS));
}
The implmentation from my idea:
@Test
public void insertWithRepeatString() {
final int n = 100000;
final String one = "MonkeyPony";
final String two = "Monkey";
final Stopwatch sw = new Stopwatch();
int x = 1;
for (; x <= 5; x++) { // loop 4 times (warming up) to avoid JIT
System.out.println("warming up times:" + x);
if (x == 5) {
sw.start();
}
final StringBuilder builder = new StringBuilder(one);
final int m = two.length() / 2;
final String h1 = two.substring(0, m); //get Mon
final String r1 = two.substring(m); //get Key
final String head = new String(new char[n - 1]).replace("\0", h1); //build repeat string
final String tail = new String(new char[n - 1]).replace("\0", r1); //build repeat String
final StringBuilder builder2 = new StringBuilder(head);
builder2.append(two).append(tail);
builder.insert(builder.length() / 2, builder2);
if (x == 5) {
sw.stop();
// System.out.println("builder:" + builder.toString());
}
}
System.out.println("Idea:" + sw.elapsedTime(TimeUnit.MILLISECONDS));
}
The output:
warming up times:1
warming up times:2
warming up times:3
warming up times:4
warming up times:5
Idea:41
warming up times:1
warming up times:2
warming up times:3
warming up times:4
warming up times:5
SBuilder:4413