| | 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.IncreasingDecreasingString; |
| | 15 | |
|
| | 16 | | /// <inheritdoc /> |
| | 17 | | public class IncreasingDecreasingStringDictionary : IIncreasingDecreasingString |
| | 18 | | { |
| | 19 | | /// <summary> |
| | 20 | | /// Time complexity - O(n * k * log k), where n is the length of the string and k is the number of unique charac |
| | 21 | | /// Space complexity - O(n + k), where n is the length of the string and k is the number of unique characters |
| | 22 | | /// </summary> |
| | 23 | | /// <param name="s"></param> |
| | 24 | | /// <returns></returns> |
| | 25 | | public string SortString(string s) |
| 2 | 26 | | { |
| 2 | 27 | | var dictionary = new Dictionary<char, int>(); |
| | 28 | |
|
| 39 | 29 | | foreach (var c in s.Where(c => !dictionary.TryAdd(c, 1))) |
| 9 | 30 | | { |
| 9 | 31 | | dictionary[c]++; |
| 9 | 32 | | } |
| | 33 | |
|
| 2 | 34 | | var stringBuilder = new StringBuilder(); |
| | 35 | |
|
| 5 | 36 | | while (stringBuilder.Length < s.Length) |
| 3 | 37 | | { |
| 45 | 38 | | foreach (var key in dictionary.Keys.Where(key => dictionary[key] > 0).OrderBy(c => c)) |
| 9 | 39 | | { |
| 9 | 40 | | stringBuilder.Append(key); |
| | 41 | |
|
| 9 | 42 | | dictionary[key]--; |
| 9 | 43 | | } |
| | 44 | |
|
| 36 | 45 | | foreach (var key in dictionary.Keys.Where(key => dictionary[key] > 0).OrderByDescending(c => c)) |
| 6 | 46 | | { |
| 6 | 47 | | stringBuilder.Append(key); |
| | 48 | |
|
| 6 | 49 | | dictionary[key]--; |
| 6 | 50 | | } |
| 3 | 51 | | } |
| | 52 | |
|
| 2 | 53 | | return stringBuilder.ToString(); |
| 2 | 54 | | } |
| | 55 | | } |