标签:
问题描述:Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to3999.
问题分析:{‘M‘,‘D‘,‘C‘,‘L‘,‘X‘,‘V‘,‘I‘};分别对应{1000, 500, 100, 50, 10, 5, 1};
当出现类似CM情况时,即较小者在较大者前面,则应该用较大者减去较小者,即1000-100=900;
否则则直接相加;
这里用到hashMap进行存储,get()的时间复杂度为O(1),用空间换时间
仅需注意条件判断及进位情况即可
代码:
public class Solution { public int romanToInt(String s) { if(s == null || s.length() == 0) return 0; char[] numberchars = {'M','D','C','L','X','V','I'}; int[] values = {1000, 500, 100, 50, 10, 5, 1}; HashMap<Character, Integer> map = new HashMap<>(); for(int i = 0; i < numberchars.length; i++) { map.put(numberchars[i], values[i]); } int result = 0; char[] datas = s.toCharArray(); int i = 1; int last = map.get(datas[0]); int now = 0; while(i <= datas.length) { if( i <= datas.length - 1) { now = map.get(datas[i]); if(now > last) { result += (now - last); ++i; if(i < datas.length) last = map.get(datas[i]); } else { result += last; last = now; } } else { result += last; last = now; } ++i; } return result; } }
标签:
原文地址:http://blog.csdn.net/woliuyunyicai/article/details/44984179