// DO NOT DO THIS. It is quadratic-time!
StringBuilder sb = new StringBuilder();
for(int i=0;i<100;i++){
sb.insert(0, Integer.toString(i));
}
Warning: It defeats the purpose of StringBuilder, but it does what you asked.
Better technique (although still not ideal):
- Reverse each string you want to insert.
- Append each string to a
StringBuilder. - Reverse the entire
StringBuilderwhen you're done.
This will turn an O(n²) solution into O(n).
Answer from user541686 on Stack Overflow// DO NOT DO THIS. It is quadratic-time!
StringBuilder sb = new StringBuilder();
for(int i=0;i<100;i++){
sb.insert(0, Integer.toString(i));
}
Warning: It defeats the purpose of StringBuilder, but it does what you asked.
Better technique (although still not ideal):
- Reverse each string you want to insert.
- Append each string to a
StringBuilder. - Reverse the entire
StringBuilderwhen you're done.
This will turn an O(n²) solution into O(n).
you can use strbuilder.insert(0,i);
I have this piece of code
StringBuilder sb = new StringBuilder(); if(strX.charAt(i-1)==strY.charAt(j-1)){ sb.insert(0,strX.charAt(i-1)); }
I get error on the HackerRank that terminated due to timeout. If I remove this piece of code, everything else works fine.
I was wondering if
-
this is the optimized way to keep on appending characters at the front?
-
Does this approach work?
just do a .reverse on the sb.toString() at the end.. surely that's 10x more readable
-
Inserting at index 0 has a time complexity of O(n). So if you already have 500 characters in the internal array, it needs to shift those 500 chars over just to make space for the new char at the first index. So no, it is not.
-
Yes, it works.
Do what OffbeatDrizzle suggests, or simply create a function that will iterate over the StringBuilder in reverse and print out the contents- assuming this is what is required. If you need an object then reversing it at the end is the best way.
Yes, reversing the enumerable is much faster.
For example:
var numStrings = 80000;
var strings = new List<String>();
for(var i = 0; i < numStrings; i++)
{
strings.Add(Guid.NewGuid().ToString());
}
var sw = new Stopwatch();
sw.Start();
var sb = new StringBuilder();
foreach(var str in Enumerable.Reverse(strings))
sb.Append(str);
sw.Stop();
sw.ElapsedMilliseconds.Dump(); // 13 milliseconds
sb.Dump();
sw = new Stopwatch();
sw.Start();
sb = new StringBuilder();
foreach(var str in strings)
sb.Insert(0, str);
sw.Stop();
sw.ElapsedMilliseconds.Dump(); // 42063 milliseconds
sb.Dump();
Presuming you can put them into an array, and nothing can stop you to do it if you have enough memory, Iterate the array of strings using an index in reverse order and then use append. This should be really fast.
StringBuilder s = new StringBuilder()
for(i = array.Length - 1; i >= 0; i--)
{
s.Append(array[i]);
}
Another method would be to use Reverse with Join. But the previous method should do it in a fast manner
string.Join("", array.Reverse())