LeetCode Roman to Integer

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

 1 public class Solution {
 2     public int romanToInt(String s) {
 3         int res=0;
 4         HashMap<String, Integer> map = new HashMap<String, Integer>();
 5         map.put("M", 1000);map.put("CM", 900);map.put("D", 500);map.put("CD", 400);
 6         map.put("C", 100);map.put("XC", 90);
 7         map.put("L", 50);map.put("XL", 40);map.put("X", 10);map.put("IX", 9);map.put("V", 5);
 8         map.put("IV", 4);map.put("I",1);
 9         if (s.equals("")) return 0;
10         if (s.length()==1) return map.get(s);
11         String ss;
12         for (int i = 0; i < s.length(); i++) {
13             if (i<s.length() - 1) {
14                 ss = s.substring(i, i + 2);
15             }else {
16                 ss = s.substring(i, i + 1);
17             }
18 
19             if (map.containsKey(ss)) {
20                 res = res + map.get(ss);
21                 ++i;
22             } else {
23                 ss = s.substring(i, i + 1);
24                 res = res + map.get(ss);
25             }
26         }
27         return res;
28     }
29 }

 

posted @ 2014-11-26 23:52  birdhack  阅读(116)  评论(0编辑  收藏  举报