The task is the following: "Write a JavaScript program to find the shortest possible string which can create a string to make it a palindrome by adding characters to the end of it."
This is the code I am looking at:
function build_Palindrome(new_str) {
var flag;
for (var i = new_str.length;; i++) {
flag = true;
for (var j = 0; j < i - j - 1; j++) {
if (i - j - 1 < new_str.length && new_str[j] != new_str[i - j - 1]) {
flag = false;
break;
}
}
if (flag) {
for (var j = new_str.length; j < i; j++) {
new_str += new_str[i - j - 1];
}
return new_str;
}
}
}
Test:
console.log(build_Palindrome("abcddc"))
Output:
abcddcba
My question: At first it starts with j=0
. If in the for
loop, flag=false
, then how does it proceed? Is i=7
(i++
?) and is j=0
or j=1
?