|
| 1 | +/** |
| 2 | + * 1405. Longest Happy String |
| 3 | + * https://leetcode.com/problems/longest-happy-string/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * A string s is called happy if it satisfies the following conditions: |
| 7 | + * - s only contains the letters 'a', 'b', and 'c'. |
| 8 | + * - s does not contain any of "aaa", "bbb", or "ccc" as a substring. |
| 9 | + * - s contains at most a occurrences of the letter 'a'. |
| 10 | + * - s contains at most b occurrences of the letter 'b'. |
| 11 | + * - s contains at most c occurrences of the letter 'c'. |
| 12 | + * |
| 13 | + * Given three integers a, b, and c, return the longest possible happy string. If there are |
| 14 | + * multiple longest happy strings, return any of them. If there is no such string, return |
| 15 | + * the empty string "". |
| 16 | + * |
| 17 | + * A substring is a contiguous sequence of characters within a string. |
| 18 | + */ |
| 19 | + |
| 20 | +/** |
| 21 | + * @param {number} a |
| 22 | + * @param {number} b |
| 23 | + * @param {number} c |
| 24 | + * @return {string} |
| 25 | + */ |
| 26 | +var longestDiverseString = function(a, b, c) { |
| 27 | + const counts = [ |
| 28 | + { char: 'a', count: a }, |
| 29 | + { char: 'b', count: b }, |
| 30 | + { char: 'c', count: c } |
| 31 | + ]; |
| 32 | + const result = []; |
| 33 | + |
| 34 | + while (true) { |
| 35 | + counts.sort((x, y) => y.count - x.count); |
| 36 | + |
| 37 | + let added = false; |
| 38 | + for (let i = 0; i < 3; i++) { |
| 39 | + const { char, count } = counts[i]; |
| 40 | + if (count === 0) continue; |
| 41 | + |
| 42 | + const total = result.length; |
| 43 | + if (total >= 2 && result[total - 1] === char && result[total - 2] === char) { |
| 44 | + continue; |
| 45 | + } |
| 46 | + |
| 47 | + result.push(char); |
| 48 | + counts[i].count--; |
| 49 | + added = true; |
| 50 | + break; |
| 51 | + } |
| 52 | + |
| 53 | + if (!added) break; |
| 54 | + } |
| 55 | + |
| 56 | + return result.join(''); |
| 57 | +}; |
0 commit comments