Home > Enterprise >  Function to determine if it is possible to make the one string to be equal with the other
Function to determine if it is possible to make the one string to be equal with the other

Time:02-11

function to determine if it is possible to make the first input equal to the second input by either capitalizing or removing letters. Cannot interchange the positions of the letters.

CodePudding user response:

const canReplace = (str1, str2) => {
  const letters1 = str1.split('')
  const letters2 = str2.split('')
  let lastIdx = -1

  for (let l2 of letters2) {
    const idx = letters1.findIndex(l1 => l2 === l1 || l2.toLowerCase() === l1)
    if (idx > lastIdx) {
      lastIdx = idx
    } else {
      return false
    }
  }

  return lastIdx !== -1

}

console.log(canReplace('abCde', 'BCD'))
console.log(canReplace('Abcdef', 'ACE'))
console.log(canReplace('ABCD', 'CBD'))
console.log(canReplace('ABC', 'AbC'))

CodePudding user response:

Idea is to take one letter at a time from right string, and try to “cross out” some letters from left string by certain rules. For each letter from right string, it must be able to cross out at least one letter from left string, otherwise the check fails.

function check(left, right) {
  const chars = right.split('');
  for (const c of chars) {
    let i = left.indexOf(c);
    if (i == -1) i = left.indexOf(c.toLowerCase());
    if (i == -1) return false;
    left = left.slice(i   1);
  }
  return true;
}
  • Related