'How to solve this java problem efficiently [closed]
I am trying to solve this problem and I worked out a solution but its too slow, this is my approach:
- loop to add all strings in an array
- loop to concatenate strings based on inputs
- print out final concatenated string
Which works, but I need a faster approach. I am thinking of trying to determine the order of concatenation of each string, then just print strings based on the order. But I have no idea how to determine the order in the first place. Does anyone have any advice? Thank you!
[SOLVED] thank you guys for the help! I was able to pass the test cases.
Solution 1:[1]
Java's strings are immutable. This means that each concatenation results in a fully new copy where both a and b are copied.
You need to use Java's StringBuilder and convert the end result to a normal string. StringBuilders truely append one to the other without copying the first one. They work like a dynamic length array under the hood.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user1984 |
