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 教师闺蜜祝福语简短