在 JavaScript 中格式化字串以分離相同字元
我們要求編寫一個 JavaScript 函式,它將一個字串作為第一個且唯一的引數輸入。
該函式應嘗試重新組織字串中存在的字元,以便沒有兩個相同的字元彼此相鄰放置。
如果存在至少一個這樣的組合,那麼我們的函式應該返回該組合字串,否則我們的函式應該返回一個空字串。
例如 -
如果輸入字串為 -
const str = 'add';
那麼我們的函式可以輸出 -
const output = 'dad';
示例
以下是程式碼 -
const str = 'add'; const formatString = (str = '') => { const map = {}; for(let i = 0; i < str.length; i++){ map[str[i]] = map[str[i]] || 0; map[str[i]] ++; } let keys = Object.keys(map).sort((a, b) => { if(map[a] < map[b]){ return 1; }; return -1; }); let flag = str.length%2?(Math.floor(str.length/2)+1):str.length/2; if(map[keys[0]] > flag){ return ""; }; const res = []; let index = 0, max = str.length-1; while(keys.length){ let currKey = keys.shift(); let count = map[currKey]; while(count){ res[index] = currKey; index = index+2; if(index>max) index=1; count--; } } return res.join(""); }; console.log(formatString(str));
輸出
以下是控制檯輸出 -
dad
廣告