Longest Happy String in JavaDetermine the longest happy string that may be given the three integers a, b, and c. Return any of the longest happy strings if more than one exists. Return the empty string " if there isn't a string of that kind. A string that has a continuous string of characters is called a substring. The conditions that follow must be met for a string str to be considered as a happy string:
Example 1: Input: int a = 1 int b = 1 int c = 7 Output: The longest happy string is "ccaccbcc" Explanation: An additional suitable answer might be also "ccbccacc". Example 2: Input: int a = 7 int b = 1 int c = 0 Output: The longest happy string is "aabaa" Explanation: In this instance, that is the only suitable answer. Approach: Using Greedy AlgorithmWe strongly pick two characters since the letter has the maximum count. However, we only take one character for letters that don't have the maximum count. The letter with a lower count would be utilized as a delimiter, which is the reason. We want to greedily do two things in order to get the longest happy string possible.
After appending the letters to the result for each loop, we reevaluate which letter has the maximum count. Follow 1 and include two characters if it is the maximum; if not, follow 2 and only append one. The count of all the letters is then rearranged. Continuing in the same way until we had used up every letter with a lower count. Algorithm:Step 1: Priority Queue has a fixed order (Pair.cnt). Step 2: If cnt is greater than zero, add char and count to PQ. Step 3: If size is greater than two (if (p_one.cnt >= 2)), append two characters (from p_one); if not, insert one character only. Step 4: If size is more than two and p_one.cnt is less than p_two.cnt, append two characters (from p_two). If not, add simply one character. Step 5: Verify that the Priority Queue is empty at the conclusion. If not, append in the instance that the characters differ. Implementation:FileName: HappyString.java Output: The Longest Happy String is given by : ccaccbcc Complexity Analysis: The Time Complexity is O(a+b+c), and the Space Complexity is O(a+b+c). The operations pertaining to the PriorityQueue and the counts of the corresponding characters, a, b, and c, are assumed in this complexity analysis. |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India