用 JavaScript 根據字元頻率對字串進行編碼


問題

我們要求編寫一個 JavaScript 函式,其將一個字串 str 作為第一個且唯一的引數。

我們的函式應當基於輸入字串建立一個新字串,其中新字串中的每個字元如果在原始字串中僅出現一次,則為 '(',如果在原始字串中出現多次,則為 ')'

而且我們應當忽略大小寫

例如,如果函式的輸入是 -

輸入

const str = 'Success';

輸出

const output = ')())())';

示例

以下是程式碼 -

 線上演示

const str = 'Success';
const mapString = (str = '') => {
   const mainStr = str.toLowerCase()
   const hash = {}
   let res = ''
   for (let char of mainStr) {
      hash[char] = ~~hash[char] + 1
   }
   for (let char of mainStr) {
      if (hash[char] > 1) {
      res += ')'
   } else {
      res += '('
   }
}
   return res
};
console.log(mapString(str));

輸出

)())())

更新日期: 2021-04-22

145 次瀏覽

開啟你的職業生涯

完成課程以獲取認證

開始
廣告
© . All rights reserved.