Java Solution Can it be optimized?


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

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.