| | 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 | | namespace LeetCode.Algorithms.SortingTheSentence; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class SortingTheSentenceIterative : ISortingTheSentence |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n + m * l), where n is the length of the input string, m is the number of words, and l i |
| | 19 | | /// the average length of these words. Since n is essentially m * l (each character in the input string is part |
| | 20 | | /// of a word), the time complexity simplifies to O(n) |
| | 21 | | /// Space complexity - O(m), where m is the number of words |
| | 22 | | /// </summary> |
| | 23 | | /// <param name="s"></param> |
| | 24 | | /// <returns></returns> |
| | 25 | | public string SortSentence(string s) |
| 2 | 26 | | { |
| 2 | 27 | | var wordsWithIndexes = s.Split(' '); |
| | 28 | |
|
| 2 | 29 | | var words = new string[wordsWithIndexes.Length]; |
| | 30 | |
|
| 22 | 31 | | foreach (var wordsWithIndex in wordsWithIndexes) |
| 8 | 32 | | { |
| 8 | 33 | | var index = (int)char.GetNumericValue(wordsWithIndex.Last()) - 1; |
| | 34 | |
|
| 8 | 35 | | words[index] = wordsWithIndex[..^1]; |
| 8 | 36 | | } |
| | 37 | |
|
| 2 | 38 | | return string.Join(' ', words); |
| 2 | 39 | | } |
| | 40 | | } |