返回 JavaScript 字串中首次重複字元的索引


我們需要編寫一個 JavaScript 函式,該函式接受一個字串並返回字串中首次出現兩次的字元的索引。

如果不存在這樣的字元,則我們應返回 -1。以下是我們的字串 −

const str = 'Hello world, how are you';

示例

以下為程式碼 −

const str = 'Hello world, how are you';
const firstRepeating = str => {
   const map = new Map();
   for(let i = 0; i < str.length; i++){
      if(map.has(str[i])){
         return map.get(str[i]);
      };
      map.set(str[i], i);
   };
   return -1;
};
console.log(firstRepeating(str));

輸出

控制檯輸出如下 −

2

更新於:16-Sep-2020

168 次瀏覽

啟動您的 職業生涯

完成課程後獲得認證

開始
廣告
© . All rights reserved.