AcWing 899. 编辑距离. (JavaScript )
原题链接
简单
作者:
cp777
,
2021-03-05 18:57:06
,
所有人可见
,
阅读 267
const N = 1010;
const M = 15;
let str = []; //给定字符串
let strs = []; //给定字符串集合 从0开始存储
let b = []; //询问字符串
let f = []; //编辑距离
for (let i = 0; i < N; i++) f[i] = new Int32Array(M);
let edit_distance = (a, b) => {
let la = a.length - 1, //a:*abcd 0位置多一个字符
lb = b.length - 1; //b:*fas
//边界
for (let i = 0; i <= la; i++) f[i][0] = i; //a前i个变为b前0个,a全删需i步
for (let i = 0; i <= lb; i++) f[0][i] = i; //a前0个变为b前i个,增i步
for (let i = 1; i <= la; i++) {
for (let j = 1; j <= lb; j++) {
f[i][j] = Math.min(f[i - 1][j] + 1, 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);
}
}
return f[la][lb];
}
let n = 0,
m = 0;
let res = 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];
m = getInputNums(line)[1];
} else if (lineIdx <= n) {
str = getInputStr(line);
str.unshift('*');
str = str.join('');
strs.push(str);
} else if (lineIdx <= n + m) {
res = 0;
arr = getInputStr(line);
b = arr[0];
let x = arr[1];
b = '*' + b //询问字符串
let d = 0; //编辑距离
for (let i = 0; i < n; i++) {
d = edit_distance(strs[i], b);
if (d <= x) res++;
}
console.log(res);
}
});
});