Leetcode

Roman to Integer

  • Time:O(n)
  • Space:O(128) = O(1)

C++

class Solution {
 public:
  int romanToInt(string s) {
    int ans = 0;
    vector<int> roman(128);

    roman['I'] = 1;
    roman['V'] = 5;
    roman['X'] = 10;
    roman['L'] = 50;
    roman['C'] = 100;
    roman['D'] = 500;
    roman['M'] = 1000;

    for (int i = 0; i + 1 < s.length(); ++i)
      if (roman[s[i]] < roman[s[i + 1]])
        ans -= roman[s[i]];
      else
        ans += roman[s[i]];

    return ans + roman[s.back()];
  }
};

JAVA

class Solution {
  public int romanToInt(String s) {
    int ans = 0;
    int[] roman = new int[128];

    roman['I'] = 1;
    roman['V'] = 5;
    roman['X'] = 10;
    roman['L'] = 50;
    roman['C'] = 100;
    roman['D'] = 500;
    roman['M'] = 1000;

    for (int i = 0; i + 1 < s.length(); ++i)
      if (roman[s.charAt(i)] < roman[s.charAt(i + 1)])
        ans -= roman[s.charAt(i)];
      else
        ans += roman[s.charAt(i)];

    return ans + roman[s.charAt(s.length() - 1)];
  }
}

SOLUTION-2
class Solution { public int romanToInt(String s) { int ans = 0; s = s.replace("IV","4") .replace("IX","9") .replace("XL","P") .replace("XC","Q") .replace("CD","R") .replace("CM","S"); for(char ch : s.toCharArray()) { switch (ch) { case 'I': ans+=1; break; case 'V': ans+=5; break; case 'X': ans+=10; break; case 'L': ans+=50; break; case 'C': ans+=100; break; case 'D': ans+=500; break; case 'M': ans+=1000; break; case '4': ans+=4; break; case '9': ans+=9; break; case 'P': ans+=40; break; case 'Q': ans+=90; break; case 'R': ans+=400; break; case 'S': ans+=900; break; } } return ans; } }

Python

class Solution:
  def romanToInt(self, s: str) -> int:
    ans = 0
    roman = {'I': 1, 'V': 5, 'X': 10, 'L': 50,
             'C': 100, 'D': 500, 'M': 1000}

    for a, b in zip(s, s[1:]):
      if roman[a] < roman[b]:
        ans -= roman[a]
      else:
        ans += roman[a]

    return ans + roman[s[-1]]