2014年4月8日 星期二

[LeetCode] Roman to Integer

Problem:
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Solution:O(n)


public class Solution {
   public int romanToInt(String s) {
    Map<Character, Integer> map = new HashMap<Character, Integer>();
    map.put('I', 1);
    map.put('V', 5);
    map.put('X', 10);
    map.put('L', 50);
    map.put('C', 100);
    map.put('D', 500);
    map.put('M', 1000);
    int ret = 0;
    char[] str = s.toCharArray();
     
    for(int i=0; i<str.length;i++){
     if(i == str.length-1 || map.get(str[i+1]) <= map.get(str[i]))
    ret+= map.get(str[i]);
  else
    ret-= map.get(str[i]);
    }
  return ret;
 }
}
Key concept:If there is a symbol larger than current symbol, 
we need to subtract current symbol value, otherwise add this symbol value  

沒有留言:

張貼留言