Simple Java solution 290ms


  • 0
    W
        	public int romanToInt(String s) {
    
        	StringBuilder sb=new StringBuilder(s);
    
            int[] map=new int['X'+1];map['I']=1;map['V']=5;map['X']=10;map['L']=50;map['C']=100;map['D']=500;map['M']=1000;
    
            //Can use HashMap, but will reduce performance. e.g. HashMap<Character,Integer> map=new HashMap<Character,Integer>();
            //map.put('I',1);map.put('V',5);map.put('X',10);map.put('L',50);map.put('C',100);map.put('D',500);map.put('M',1000);
    
            int idx=sb.length()-2;
            int ret=map[sb.charAt(s.length()-1)];
            int prev=ret;
    
            while(idx>=0){
    
                 int num=map[sb.charAt(idx)];
                 if(num<prev) ret-=num;
                 else ret+=num;
    
                 prev=num;
                 idx--;
    
                }
    
            return ret;
    
            }

Log in to reply
 

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