2ms simple java solution (100ms total runtime)


  • 1
    F
    public int romanToInt(String s) {
            Hashtable<Character,Integer> h=new Hashtable<Character,Integer>();
            h.put('I',1);
            h.put('V',5);
            h.put('X',10);
            h.put('L',50);
            h.put('C',100);
            h.put('D',500);
            h.put('M',1000);
            int result=h.get(s.charAt(0));
            int prev=result;
            for(int i=1;i<s.length();i++){
                int curr=h.get(s.charAt(i));
                if(curr>prev)
                    result+=curr-2*prev;
                else
                    result+=curr;
                prev=curr;
            }
            return result;    
        }
    

Log in to reply
 

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