Solución
solution.tsTypeScript
function editDistance(source: string, target: string): number {
if (source === target) return 0;
if (target.trim() === "") return source.length;
let distance = 0;
let isSourceLarger = source.length > target.length;
let big = isSourceLarger ? source : target;
let short = isSourceLarger ? target : source;
let bigList = isSourceLarger ? source.split('') : target.split("");
let shortList = isSourceLarger ? target.split('') : source.split("");
if(big.includes(short)) return big.replace(short, "").length;
const hasDifferentLengths = bigList.length !== shortList.length;
let previousComparedChar: string | undefined = "";
for (const [index, char] of bigList.entries()) {
let comparedChar = shortList.at(index);
if (char === comparedChar) {
previousComparedChar = "";
continue;
}
if (hasDifferentLengths && char === previousComparedChar) {
previousComparedChar = comparedChar;
continue;
}
distance += 1;
previousComparedChar = comparedChar;
}
return distance;
}
console.log(editDistance('xyabc', 'abc'));
console.log(editDistance('xaybzc', 'abc'));
// No modificar: necesario para evaluar el resultado.
export { editDistance };1respuestas