Simplest way to append is just using + as in s = s + c. This isn't the best way to do it performance wise since a new String is created every time (due to Strings being immutable). Instead you may use a StringBuilder e.g.
//Create outside of loop
StringBuilder sb = new StringBuilder();
//Append in loop
sb.append(c);
//Print when done
System.out.println(sb);
//Return the String to the caller
return sb.toString();
Answer from Jotunacorn on Stack OverflowVideos
Simplest way to append is just using + as in s = s + c. This isn't the best way to do it performance wise since a new String is created every time (due to Strings being immutable). Instead you may use a StringBuilder e.g.
//Create outside of loop
StringBuilder sb = new StringBuilder();
//Append in loop
sb.append(c);
//Print when done
System.out.println(sb);
//Return the String to the caller
return sb.toString();
change s = ("" + c); to s+=("" + c); but i suggest you use StringBuilder
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.