0
\$\begingroup\$

The task

Given a string, split it into as few strings as possible such that each string is a palindrome.

For example, given the input string racecarannakayak, return ["racecar", "anna", "kayak"].

Given the input string abc, return ["a", "b", "c"].

const str = "racecarannakayak";

My functional solution 1

const findPalindromesIn = str => {
  let forward = "";
  let backward = "";
  const result = [];
  const isPalindrome = s => {
    forward = s + forward;
    backward = backward + s;

    if (forward.length < 2 ||
       forward !== backward) {
      return false;
    }
    result.push(forward);
    forward = backward = "";
    return true;
  };
  [...str].forEach(isPalindrome);
  return result.concat(backward.split(""));
};

console.log(findPalindromesIn(str));

My functional solution 2

const findPalindromesIn2 = str => {
  const {backward, res} = [...str].reduce((acc,s) => {
    acc.forward = `${s}${acc.forward}`;
    acc.backward = `${acc.backward}${s}`;
    if (acc.forward.length > 1 &&
        acc.forward === acc.backward) {
      acc.res.push(acc.forward);
      acc.forward = acc.backward = "";
    }
    return acc;
  }, {forward: "", backward: "", res: []});
  return res.concat(backward.split(""));
};

console.log(findPalindromesIn2(str));

My imperative solution

function findPalindromesIn3(str) {
  let forward = "";
  let backward = "";
  const res = [];
  for (let i = 0, len = str.length; i < len; i++) {
    const s = str[i];
    forward = s + forward;
    backward = backward + s;
    if (forward.length > 1 && forward === backward) {
      res.push(forward);
      forward = backward = "";
    }
  }

  return res.concat(backward.split(""));
}

console.log(findPalindromesIn3(str));;

The solutions are all quite similar. Does anyone know a total different approach?

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.