將字串的唯一字元對映到陣列 - JavaScript


我們需要編寫一個 JavaScript 函式,傳入一個字串並開始從 0 對映其字元。每次函式遇到一個唯一的(非重複)字元時,它應將對映計數增加 1,否則為重複字元對映相同的數字。

例如 − 如果字串為 −

const str = 'heeeyyyy';

那麼輸出應為 −

const output = [0, 1, 1, 1, 2, 2, 2, 2];

示例

以下是程式碼 −

const str = 'heeeyyyy';
const mapString = str => {
   const res = [];
   let curr = '', count = -1;
   for(let i = 0; i < str.length; i++){
      if(str[i] === curr){
         res.push(count);
      }else{
         count++;
         res.push(count);
         curr = str[i];
      };
   };
   return res;
};
console.log(mapString(str));

輸出

以下是控制檯中的輸出 −

[
   0, 1, 1, 1,
   2, 2, 2, 2
]

更新於: 18-9-2020

355 次檢視

開啟您的職業生涯

透過完成課程獲得認證

開始
廣告