标签:leetcode
https://oj.leetcode.com/problems/roman-to-integer/
http://fisherlei.blogspot.com/2012/12/leetcode-roman-to-integer.html
// Symbol Value // I 1 // V 5 // X 10 // L 50 // C 100 // D 500 // M 1,000 public class Solution { public int romanToInt(String s) { Map<Character, Integer> map = new HashMap<>(); 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); char[] chars = s.toCharArray(); Character lastChar = null; int toReturn = 0; for (int i = 0 ; i < chars.length ; i ++) { char curChar = chars[i]; int curValue = map.get(curChar); Integer lastValue = lastChar == null ? null : map.get(lastChar); if (lastValue == null || lastValue >= curValue) { toReturn += curValue; } else { // Last char is wrong toReturn -= lastValue; toReturn += (curValue - lastValue); } lastChar = curChar; } return toReturn; } }
标签:leetcode
原文地址:http://7371901.blog.51cto.com/7361901/1598411