Home > database >  Javascript function to determine if it is possible to make the first input equal to the second input
Javascript function to determine if it is possible to make the first input equal to the second input

Time:02-11

Need help with a Javascript function to determine if it is possible to make the first input equal to the second input only by either capitalizing or discarding letters in the first string. Cannot interchange the positions of the letters.

Few examples:

('abCde','BCD') --> True
('Abcdef','ACE') --> True
('ABCD','CBD') --> False (Cannot change first string)
('ABC','AbC') --> False (B cannot be lowercased)

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