FTPrep, 13 Roman to integer

来源:互联网 发布:知乎第一次和女票接吻 编辑:程序博客网 时间:2024/05/22 07:19

于上一题相反,但是套路有变,相同的地方是维护一个table,但这个table只要有7 罗马数字的symbol,重点是:遍历每个字母时,比较它和它左边字母所对应的数字的大小关系,如果是小于等于那就是正常的加法,如果是大于,就是减法。

代码上注意的两点:

1,单个字母的string。string是从右到左遍历。index是右边第二个 len-2 开始,因为len-1提前加了。

2,map的key是字母,而不是string的index,所以:string+index --> key (+ map) --> value


public class Solution {    public int romanToInt(String s) {        HashMap<Character, Integer> table = new HashMap<>();        table.put('I', 1);        table.put('V', 5);        table.put('X', 10);        table.put('L', 50);        table.put('C', 100);        table.put('D', 500);        table.put('M', 1000);                int len=s.length();        int result =0;        if(len==1) return table.get(s.charAt(0));        result+=table.get(s.charAt(len-1));        for(int i=len-2; i>=0; --i){            if(table.get(s.charAt(i))<table.get(s.charAt(i+1))) result-=table.get(s.charAt(i));            else result+=table.get(s.charAt(i));        }        return result;    }}


原创粉丝点击