13. Roman to Integer

substring要是取不到东西不会返回"" 而是什么都不返回,所以不能用== "" 判断 要用长度来判断。

 

 1 class Solution {
 2     public int romanToInt(String s) {
 3         if(s == null || s == "") return 0;
 4         HashMap<String, Integer> map = new HashMap<>();
 5         map.put( "I", 1);
 6         map.put("IV", 4);
 7         map.put("V", 5);
 8         map.put("IX", 9);
 9         map.put("X", 10);
10         map.put("XL", 40);
11         map.put("L", 50);
12         map.put("XC", 90);
13         map.put("C", 100);
14         map.put("CD", 400);
15         map.put("D", 500);
16         map.put("CM", 900);
17         map.put("M", 1000);
18         
19         StringBuilder sb = new StringBuilder(s);
20         int res = 0;
21         while(s.length() > 0) {
22             if(sb.length()> 1 && map.containsKey(sb.substring(0, 2))) {
23                 res += map.get(sb.substring(0, 2));
24                 sb.delete(0, 2);
25                 s= s.substring(2);
26             }else if(sb.length() > 1) {
27                 res += map.get(sb.substring(0, 1));
28                 sb.delete(0, 1);
29                 s = s.substring(1);
30             }else {
31                 res += map.get(sb.toString());
32                 sb.delete(0, 1);
33                 s = "";
34             }
35             
36         }
37         return res;
38     }
39 }

 

posted @ 2018-09-06 09:11  jasoncool1  阅读(96)  评论(0编辑  收藏  举报