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 ]

更新於: 2021 年 4 月 24 日

141 瀏覽量

開啟您的 職業

完成課程可獲得認證

開始
廣告
© . All rights reserved.