JSFiddle - React, Tailwind, and code Playground

by nate

JavaScript

function canBePalindrome(str) {
	let failures = 0;
  let arr = str.split('');
  
  while (arr.length && failures < 2) {
  	let char = arr.shift();
    const index = arr.indexOf(char);
    if (index === -1) {
    	failures += 1;
    } else {
    	arr.splice(index, 1);
    }
  }
  
  return failures < 2;
}

const tests = [
	'aabba', // true
  'abaabb', // false
  'aaab', // false
  'abababa', // true
  'aaabbbc', // false
  'civic', // true
  'ivicc', // true
  'civil', // false
  'livci' // false
];

tests.forEach(test => console.log(canBePalindrome(test)));