用 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
]

更新於: 19-Oct-2020

110 次瀏覽

開啟您的職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.