| | | 1 | | // -------------------------------------------------------------------------------- |
| | | 2 | | // Copyright (C) 2026 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 LeetCode.Algorithms.RomanToInteger.Iterative; |
| | | 13 | | |
| | | 14 | | namespace LeetCode.Algorithms.RomanToInteger; |
| | | 15 | | |
| | | 16 | | /// <inheritdoc /> |
| | | 17 | | public sealed class RomanToIntegerIterative : IRomanToInteger |
| | | 18 | | { |
| | | 19 | | /// <summary> |
| | | 20 | | /// Time complexity - O(n) |
| | | 21 | | /// Space complexity - O(n) |
| | | 22 | | /// </summary> |
| | | 23 | | /// <param name="romanString"></param> |
| | | 24 | | /// <returns></returns> |
| | | 25 | | public int RomanToInt(string romanString) |
| | 3 | 26 | | { |
| | 3 | 27 | | List<RomanNumeral> romanNumerals = []; |
| | | 28 | | |
| | 30 | 29 | | for (var i = 0; i < romanString.Length; i++) |
| | 12 | 30 | | { |
| | 12 | 31 | | var currentChar = romanString.ElementAt(i); |
| | 12 | 32 | | var nextChar = romanString.ElementAtOrDefault(i + 1); |
| | | 33 | | |
| | 12 | 34 | | var subtractiveRomanNumeral = SubtractiveRomanNumeral.SubtractiveRomanNumerals.FirstOrDefault(s => |
| | 76 | 35 | | s.Symbol.Char.Equals(currentChar) && s.SecondSymbol.Char.Equals(nextChar)); |
| | | 36 | | |
| | 12 | 37 | | if (subtractiveRomanNumeral != null) |
| | 3 | 38 | | { |
| | 3 | 39 | | romanNumerals.Add(subtractiveRomanNumeral); |
| | 3 | 40 | | i++; |
| | 3 | 41 | | } |
| | | 42 | | else |
| | 9 | 43 | | { |
| | 28 | 44 | | romanNumerals.Add(RomanNumeral.RomanNumerals.First(s => s.Symbol.Char.Equals(currentChar))); |
| | 9 | 45 | | } |
| | 12 | 46 | | } |
| | | 47 | | |
| | 15 | 48 | | return romanNumerals.Sum(romanNumeral => romanNumeral.Value); |
| | 3 | 49 | | } |
| | | 50 | | } |