알고리즘/codefights

45>buildPalindrome

Diademata 2017. 11. 3. 23:53
반응형

Given a string, find the shortest possible string which can be achieved by adding characters to the end of initial string to make it a palindrome.


Example


For st = "abcdc", the output should be

buildPalindrome(st) = "abcdcba".


code>>


std::string buildPalindrome(std::string s) {

int sz = s.size();

for (;; ++sz)

{

bool f = true;

for (int i = sz - s.size(); i<sz / 2; ++i)

{

if (s[i] != s[sz - i - 1])

f = false;

}

if (f)break;

}

for (int i = s.size(); i<sz; ++i)

{

s.push_back(s[sz - i - 1]);

}

return s;

}

반응형