1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
|
var longestDiverseString = function (a, b, c) { const num = { a: { num: a, char: "a" }, b: { num: b, char: "b" }, c: { num: c, char: "c" }, };
const calculate = () => { let total = 0, flag = false, onlyOne = true, restKey, restNum;
const numArr = []; for (const key in num) { const element = num[key]; numArr.push(num[key]); total += element.num; if (element.num) { if (!flag) { flag = true; restKey = key; restNum = element.num; continue; } if (flag) { onlyOne = false; restKey = ""; restNum = 0; } } }
numArr.sort((a, b) => a.num - b.num);
return { min: numArr[0], middle: numArr[1], max: numArr[2], total, onlyOne, restKey, restNum, }; };
let res = "", count = 0, prev;
while (true) { const { min, middle, max, total, onlyOne, restKey } = calculate(); if (total <= 0 || onlyOne) break;
let target;
const array = [max, middle, min];
for (let i = 0; i < array.length; i++) { const cur = array[i]; const { num: curNum, char } = cur; if (char === prev || curNum <= 0) continue; target = cur; prev = char;
let repeatNum = 1;
if (i === 0) repeatNum = curNum > 2 ? 2 : curNum;
res += char.repeat(repeatNum); num[char].num -= repeatNum; break; } }
const { onlyOne, restKey, restNum } = calculate();
if (onlyOne) { const repeatNum = restNum > 2 ? 2 : restNum; return `${res}${restKey.repeat(repeatNum)}`; }
return res; };
|