| | 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.RomanToInteger; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class RomanToIntegerDictionary : IRomanToInteger |
| | 16 | | { |
| 3 | 17 | | private readonly Dictionary<string, int> _romanIntegersDictionary = new() |
| 3 | 18 | | { |
| 3 | 19 | | { "IV", 4 }, |
| 3 | 20 | | { "IX", 9 }, |
| 3 | 21 | | { "XL", 40 }, |
| 3 | 22 | | { "XC", 90 }, |
| 3 | 23 | | { "CD", 400 }, |
| 3 | 24 | | { "CM", 900 }, |
| 3 | 25 | | { "I", 1 }, |
| 3 | 26 | | { "V", 5 }, |
| 3 | 27 | | { "X", 10 }, |
| 3 | 28 | | { "L", 50 }, |
| 3 | 29 | | { "C", 100 }, |
| 3 | 30 | | { "D", 500 }, |
| 3 | 31 | | { "M", 1000 } |
| 3 | 32 | | }; |
| | 33 | |
|
| | 34 | | /// <summary> |
| | 35 | | /// Time complexity - O(n) |
| | 36 | | /// Space complexity - O(1) |
| | 37 | | /// </summary> |
| | 38 | | /// <param name="romanString"></param> |
| | 39 | | /// <returns></returns> |
| | 40 | | public int RomanToInt(string romanString) |
| 3 | 41 | | { |
| 3 | 42 | | var result = 0; |
| 3 | 43 | | var i = 0; |
| | 44 | |
|
| 15 | 45 | | while (i < romanString.Length) |
| 12 | 46 | | { |
| 12 | 47 | | if (i < romanString.Length - 1 && |
| 12 | 48 | | _romanIntegersDictionary.TryGetValue(romanString.Substring(i, 2), out var value)) |
| 3 | 49 | | { |
| 3 | 50 | | result += value; |
| 3 | 51 | | i += 2; |
| 3 | 52 | | } |
| | 53 | | else |
| 9 | 54 | | { |
| 9 | 55 | | if (_romanIntegersDictionary.TryGetValue(romanString.Substring(i, 1), out var value1)) |
| 9 | 56 | | { |
| 9 | 57 | | result += value1; |
| 9 | 58 | | } |
| | 59 | |
|
| 9 | 60 | | i++; |
| 9 | 61 | | } |
| 12 | 62 | | } |
| | 63 | |
|
| 3 | 64 | | return result; |
| 3 | 65 | | } |
| | 66 | | } |