Simplest C# Solution with HashMap 1 core if statement O(n)


  • 0
    C

    public class Solution {
    public int RomanToInt(string s) {

        Dictionary<char, int> romanMap = new Dictionary<char, int>();
        romanMap.Add('I', 1);
        romanMap.Add('V', 5);
        romanMap.Add('X', 10);
        romanMap.Add('L', 50);
        romanMap.Add('C', 100);
        romanMap.Add('D', 500);
        romanMap.Add('M', 1000);
        
        if (s.Length == 1)
        {
            return romanMap[s[0]];
        }
        
        var result = romanMap[s[0]];
        
        for (int i=1; i < s.Length; i++)
        {
            if (romanMap[s[i-1]] < romanMap[s[i]])
            {
                // add the current number
                result += romanMap[s[i]];
                
                // we need to subtract the one that is already added 
                // and subtract again to get the right count.
                // for cases like IV meaning 1 removed from 5.
                result -=  (romanMap[s[i-1]] * 2);
            }
            else
            {
                result += romanMap[s[i]];
            }
        }
        
        return result;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.