I am relatively new to C++. I was practicing a coding problem and it was related to converting a string to palindrome.
I was storing the alphabets' count in a vector and later generating the palindrome like this -
string palindrome_string;
for (short i = 0; i < 26; ++i) {
alphabet_count[i] /= 2;
for (short j = 0; j < alphabet_count[i]; ++j)
palindrome_string += string(1, static_cast<char>('a' + i));
}
But for a particular test case (input containing 2.10^5 es only), the program was exceeding the memory limit of 256 MB. Then I replaced the inner loop just with this statement -
palindrome_string += string(alphabet_count[i], static_cast<char>('a' + i));
and the program ran fine with only using around 2.4 MB.
So I want to ask if this is related to the performance with using concatenation vs the constructor function, and if yes, what is/are the possible reason/s?
If it matters, I compiled the program with MS VC++ 2010.
If it helps, here are the submissions (the code) - the failed one (test case: 10) and the successful one.