LeetCode 1405. Longest Happy String Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
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 1: Greedy + Priority Queue

The greedy strategy is to prioritize the selection of characters with the most remaining occurrences. By using a priority queue or sorting, we ensure that the character selected each time is the one with the most remaining occurrences (to avoid having three consecutive identical characters, in some cases, we need to select the character with the second most remaining occurrences).

PythonJavaC++GoTypeScript
class Solution: def longestDiverseString(self, a: int, b: int, c: int) -> str: h = [] if a > 0: heappush(h, [-a, 'a']) if b > 0: heappush(h, [-b, 'b']) if c > 0: heappush(h, [-c, 'c']) ans = [] while len(h) > 0: cur = heappop(h) if len(ans) >= 2 and ans[-1] == cur[1] and ans[-2] == cur[1]: if len(h) == 0: break nxt = heappop(h) ans.append(nxt[1]) if -nxt[0] > 1: nxt[0] += 1 heappush(h, nxt) heappush(h, cur) else: ans.append(cur[1]) if -cur[0] > 1: cur[0] += 1 heappush(h, cur) return ''.join(ans)(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !