SImple python O(n) solution using dictionary


#1

class Solution:
# @param A : string
# @return an integer
def romanToInt(self,A):
data = {‘I’: 1, ‘V’: 5, ‘X’: 10, ‘L’: 50, ‘C’: 100, ‘D’: 500, ‘M’: 1000}

    count = 0
    flag = True

    i = 0
    while i < len(A)-1:

        if data[A[i + 1]] > data[A[i]]:
            count += data[A[i + 1]] - data[A[i]]
            flag = False
            i += 2

        else:
            count += data[A[i]]
            flag = True
            i += 1

    if i != len(A):
        return count + data[A[-1]]
    
    return count

#print(romanToInt(“MMCDLXXV”))