Straightforward Java solution O(n).


  • 1
    L
    public class Solution {
        private HashMap<Character,Integer> rmchars = new HashMap<Character,Integer>();
        
        private void initial(){
            rmchars.put('i',1);
            rmchars.put('v',5);
            rmchars.put('x',10);
            rmchars.put('l',50);
            rmchars.put('c',100);
            rmchars.put('d',500);
            rmchars.put('m',1000);
        }
        
        public int romanToInt(String s) {
            initial();
            char[] romanchars = s.toLowerCase().toCharArray();
            if(romanchars.length==0)
                return 0;
            int i;
            int rmint = 0;
            for(i=0;i<romanchars.length;i++){
                if(!valid(romanchars[i])){
                    return 0;
                }
                int current = rmchars.get(romanchars[i]);
                if(i==romanchars.length-1){
                    rmint += current;
                    break;
                }
                int next = rmchars.get(romanchars[i+1]);
                if(current<next){
                    rmint -= current;
                }else{
                    rmint += current;
                }
            }
            
            return rmint;
        }
        
        private boolean valid(char c){
            return rmchars.containsKey(c);
        }
    }

Log in to reply
 

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