Skip to content

1405. Longest Happy String

Description

A string s is called happy if it satisfies the following conditions:

  • s only contains the letters 'a', 'b', and 'c'.
  • s does not contain any of "aaa", "bbb", or "ccc" as a substring.
  • s contains at most a occurrences of the letter 'a'.
  • s contains at most b occurrences of the letter 'b'.
  • s contains at most c occurrences of the letter 'c'.

Given three integers a, b, and c, return the longest possible happy string. If there are multiple longest happy strings, return any of them. If there is no such string, return the empty string "".

A substring is a contiguous sequence of characters within a string.

 

Example 1:

Input: a = 1, b = 1, c = 7
Output: "ccaccbcc"
Explanation: "ccbccacc" would also be a correct answer.

Example 2:

Input: a = 7, b = 1, c = 0
Output: "aabaa"
Explanation: It is the only correct answer in this case.

 

Constraints:

  • 0 <= a, b, c <= 100
  • a + b + c > 0

 

Solutions

Solution: Greedy

  • Time complexity: O(n)
  • Space complexity: O(1)

 

JavaScript

js
/**
 * @param {number} a
 * @param {number} b
 * @param {number} c
 * @return {string}
 */
const longestDiverseString = function (a, b, c) {
  const n = a + b + c;
  let result = '';
  let repeat = 1;

  const checkRepeat = (count, previous, target) => {
    return repeat === 2 && count && previous !== target;
  };

  for (let index = 0; index < n; index++) {
    const previous = result[index - 1];

    if ((a && a >= b && a >= c && repeat < 2) || checkRepeat(a, previous, 'a')) {
      result += 'a';
      a -= 1;
    } else if ((b && b >= a && b >= c && repeat < 2) || checkRepeat(b, previous, 'b')) {
      result += 'b';
      b -= 1;
    } else if ((c && c >= a && c >= b && repeat < 2) || checkRepeat(c, previous, 'c')) {
      result += 'c';
      c -= 1;
    }

    if (!result[index]) return result;

    repeat = result[index] === previous ? repeat + 1 : 1;
  }
  return result;
};

Released under the MIT license