AcWing 902. 最短编辑距离. (Javascript)
原题链接
简单
作者:
cp777
,
2021-03-05 17:07:40
,
所有人可见
,
阅读 266
const N = 1010;
let a = [];
let b = [];
let f = [];
for (let i = 0; i < N; i++) f[i] = new Int32Array(N);
let n = 0,
m = 0;
let buf = '';
process.stdin.on('readable', function () {
let chunk = process.stdin.read();
if (chunk) buf += chunk.toString();
});
let getInputNums = line => line.split(' ').filter(s => s !== '').map(x => parseInt(x));
let getInputStr = line => line.split(' ').filter(s => s !== '');
process.stdin.on('end', function () {
buf.split('\n').forEach(function (line, lineIdx) {
if (lineIdx === 0) {
n = getInputNums(line)[0];
} else if (lineIdx === 1) {
a = getInputStr(line);
a.unshift('*');
a = a.join('');
} else if (lineIdx === 2) m = getInputNums(line)[0];
else if (lineIdx === 3) {
b = getInputStr(line);
b.unshift('*');
b = b.join('');
for (let i = 0; i <= n; i++) f[i][0] = i; //初始化 -- 删 从有到无
for (let i = 0; i <= m; i++) f[0][i] = i; //初始化 -- 增 从无到有
for (let i = 1; i <= n; i++) {
for (let j = 1; j <= m; j++) {
f[i][j] = Math.min(f[i - 1][j], f[i][j - 1]) + 1;
if (a[i] === b[j]) f[i][j] = f[i - 1][j - 1];
else f[i][j] = Math.min(f[i][j], f[i - 1][j - 1] + 1);
}
}
console.log(f[n][m]);
}
});
});