| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | using System.Text; |
| | 13 | |
|
| | 14 | | namespace LeetCode.Algorithms.LongestHappyString; |
| | 15 | |
|
| | 16 | | /// <inheritdoc /> |
| | 17 | | public class LongestHappyStringGreedy : ILongestHappyString |
| | 18 | | { |
| | 19 | | /// <summary> |
| | 20 | | /// Time complexity - O(a + b + c) |
| | 21 | | /// Space complexity - O(a + b + c) |
| | 22 | | /// </summary> |
| | 23 | | /// <param name="a"></param> |
| | 24 | | /// <param name="b"></param> |
| | 25 | | /// <param name="c"></param> |
| | 26 | | /// <returns></returns> |
| | 27 | | public string LongestDiverseString(int a, int b, int c) |
| 2 | 28 | | { |
| 2 | 29 | | var stringBuilder = new StringBuilder(); |
| | 30 | |
|
| 2 | 31 | | var counts = new List<(int Count, char Char)>(); |
| | 32 | |
|
| 2 | 33 | | if (a > 0) |
| 2 | 34 | | { |
| 2 | 35 | | counts.Add((a, 'a')); |
| 2 | 36 | | } |
| | 37 | |
|
| 2 | 38 | | if (b > 0) |
| 2 | 39 | | { |
| 2 | 40 | | counts.Add((b, 'b')); |
| 2 | 41 | | } |
| | 42 | |
|
| 2 | 43 | | if (c > 0) |
| 1 | 44 | | { |
| 1 | 45 | | counts.Add((c, 'c')); |
| 1 | 46 | | } |
| | 47 | |
|
| 15 | 48 | | while (counts.Count > 0) |
| 15 | 49 | | { |
| 30 | 50 | | counts.Sort((x, y) => y.Count.CompareTo(x.Count)); |
| | 51 | |
|
| 15 | 52 | | var isAdded = false; |
| | 53 | |
|
| 40 | 54 | | for (var i = 0; i < counts.Count; i++) |
| 18 | 55 | | { |
| 18 | 56 | | if (stringBuilder.Length >= 2 && stringBuilder[^1] == counts[i].Char && |
| 18 | 57 | | stringBuilder[^2] == counts[i].Char) |
| 5 | 58 | | { |
| 5 | 59 | | continue; |
| | 60 | | } |
| | 61 | |
|
| 13 | 62 | | stringBuilder.Append(counts[i].Char); |
| 13 | 63 | | counts[i] = (counts[i].Count - 1, counts[i].Char); |
| | 64 | |
|
| 13 | 65 | | isAdded = true; |
| | 66 | |
|
| 13 | 67 | | if (counts[i].Count == 0) |
| 3 | 68 | | { |
| 3 | 69 | | counts.Remove(counts[i]); |
| 3 | 70 | | } |
| | 71 | |
|
| 13 | 72 | | break; |
| | 73 | | } |
| | 74 | |
|
| 15 | 75 | | if (!isAdded) |
| 2 | 76 | | { |
| 2 | 77 | | break; |
| | 78 | | } |
| 13 | 79 | | } |
| | 80 | |
|
| 2 | 81 | | return stringBuilder.ToString(); |
| 2 | 82 | | } |
| | 83 | | } |