-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathsolution1.js
53 lines (50 loc) · 1.07 KB
/
solution1.js
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
/**
*
* https://leetcode-cn.com/problems/longest-happy-string/submissions/
*
* 最长快乐字符串
*
* 72ms 100.00%
* 35.7mb 100.00%
*/
const longestDiverseString = (a, b, c) => {
let ans = '';
const list = [['a', a], ['b', b], ['c', c]];
list.sort((a, b) => b[1] - a[1]);
let pre = ''
let preCount = list[0][1];
while(true) {
let currentKey;
for (let i = 0; i < 2; i++) {
const [key, count] = list[i];
if (count === 0) {
continue
}
if (key === pre) {
continue;
}
if (count === 1 || (count >= 2 && preCount > count)) {
ans += key;
list[i][1] -= 1;
} else {
ans += `${key}${key}`;
list[i][1] -= 2;
}
preCount = list[i][1];
currentKey = key;
break;
}
let count = 0;
for (let j = 0; j < 3; j++) {
if (list[j][1] === 0) {
count++;
}
}
if (count >= 2 &&( pre === currentKey || currentKey === undefined)) {
break;
}
pre = currentKey;
list.sort((a, b) => b[1] - a[1]);
}
return ans;
}