JavaScript 字符串中对应的最短距离
问题
我们需要编写一个JavaScript函数,该函数接受一串英文小写字母str作为第一个参数,以及一个存在于字符串str中的单个字符char作为第二个参数。
我们的函数应该准备并返回一个数组,对于字符串str中的每个字符,该数组包含它与由char指定的字符串中最近字符的距离。
例如,如果函数的输入是
输入
const str = 'somestring'; const char = 's';
输出
const output = [0, 1, 2, 1, 0, 1, 2, 3, 4, 5]
示例
以下是代码-
const str = 'somestring';
const char = 's';
const shortestDistance = (str = '', char = '') => {
const res = new Array(str.length).fill(Infinity)
let prev = Infinity
const handleIndex = (i) => {
if (str[i] === char) {
prev = i
}
res[i] = Math.min(res[i], Math.abs(i - prev), )
}
for (let i = 0; i < str.length; i++) {
handleIndex(i)
}
prev = Infinity
for (let i =str.length- 1; i >= 0; i--) {
handleIndex(i)
}
return res
}
console.log(shortestDistance(str, char));输出结果[ 0, 1, 2, 1, 0, 1, 2, 3, 4, 5 ]
热门推荐
10 新人红包祝福语简短精辟
11 幼师给毕业祝福语简短
12 生日高考祝福语妹妹简短
13 下飞机祝福语简短英文
14 元宵发客户祝福语简短
15 爸妈金婚文案祝福语简短
16 新郎朋友红包祝福语简短
17 虎年五一祝福语大全简短
18 出阁宴祝福语姐姐简短