Question
Given a string say "ABCD". Now create a new string with duplicates of each character in the original string and append the reverse of the same string (with duplicates) excluding the last character.
First iteration: AABBCCCCBBAA
[ABC three types of chars; Here c is the last char.Ignore duplicates after the last char c]
Second iteration: AABBBBAA
[here b is the last char]
Third iteration: AAAA
[no second char left]
Solution
#include <iostream>
#include <iomanip>
#include <string>
#include <cassert>
using namespace std;
string CreateString(const string& str)
{
assert(str.length() > 0);
string ret(str.length() * 4 - 4, ' ');
int index(0);
for (int i = 0; i < str.length() - 1; ++i)
{
ret.at(index++) = str.at(i);
ret.at(index++) = str.at(i);
}
for (int i = str.length() - 2; i >= 0; --i)
{
ret.at(index++) = str.at(i);
ret.at(index++) = str.at(i);
}
return ret;
}
int main()
{
cout << CreateString(string("a")) << endl;
cout << CreateString(string("ab")) << endl;
cout << CreateString(string("abcd")) << endl;
cout << CreateString(string("abcdefg")) << endl;
return 0;
}
Output
aaaa
aabbccccbbaa
aabbccddeeffffeeddccbbaa
Press any key to continue . . .