返回 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
安卓
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP