| | 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.ExcelSheetColumnNumber; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class ExcelSheetColumnNumberIterative : IExcelSheetColumnNumber |
| | 16 | | { |
| | 17 | | private const int ColumnsCount = 26; |
| | 18 | |
|
| 12 | 19 | | private readonly Dictionary<char, int> _columnsDictionary = new() |
| 12 | 20 | | { |
| 12 | 21 | | { 'A', 1 }, |
| 12 | 22 | | { 'B', 2 }, |
| 12 | 23 | | { 'C', 3 }, |
| 12 | 24 | | { 'D', 4 }, |
| 12 | 25 | | { 'E', 5 }, |
| 12 | 26 | | { 'F', 6 }, |
| 12 | 27 | | { 'G', 7 }, |
| 12 | 28 | | { 'H', 8 }, |
| 12 | 29 | | { 'I', 9 }, |
| 12 | 30 | | { 'J', 10 }, |
| 12 | 31 | | { 'K', 11 }, |
| 12 | 32 | | { 'L', 12 }, |
| 12 | 33 | | { 'M', 13 }, |
| 12 | 34 | | { 'N', 14 }, |
| 12 | 35 | | { 'O', 15 }, |
| 12 | 36 | | { 'P', 16 }, |
| 12 | 37 | | { 'Q', 17 }, |
| 12 | 38 | | { 'R', 18 }, |
| 12 | 39 | | { 'S', 19 }, |
| 12 | 40 | | { 'T', 20 }, |
| 12 | 41 | | { 'U', 21 }, |
| 12 | 42 | | { 'V', 22 }, |
| 12 | 43 | | { 'W', 23 }, |
| 12 | 44 | | { 'X', 24 }, |
| 12 | 45 | | { 'Y', 25 }, |
| 12 | 46 | | { 'Z', 26 } |
| 12 | 47 | | }; |
| | 48 | |
|
| | 49 | | /// <summary> |
| | 50 | | /// Time complexity - O(n) |
| | 51 | | /// Space complexity - O(1) |
| | 52 | | /// </summary> |
| | 53 | | public int TitleToNumber(string columnTitle) |
| 12 | 54 | | { |
| 12 | 55 | | var number = 0; |
| | 56 | |
|
| 92 | 57 | | for (var i = columnTitle.Length - 1; i >= 0; i--) |
| 34 | 58 | | { |
| 34 | 59 | | number += _columnsDictionary[columnTitle[i]] * (int)Math.Pow(ColumnsCount, columnTitle.Length - 1 - i); |
| 34 | 60 | | } |
| | 61 | |
|
| 12 | 62 | | return number; |
| 12 | 63 | | } |
| | 64 | | } |