Easy to understand java solution using HashMap and consider invalid input


  • 0
    W

    Although my solution is not as short as others, it shows every step clearly without fancy combination of operators and variables, making it very easy to read.
    For roman integer, we can always start from the right, when meet a smaller one, subtract it from the result, when meet a larger or equal one, add it to the result. E.g.XXIX=10-1+10+10=29.
    Note: the input cannot contains invalid characters like 'A' and one character cannot appear more than 3 times.

    public int romanToInt(String s) {
                if(s==null||s.length()==0) return -1;
                
                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 result=0;
                int current=0;
                int previous=0;
                int count=0;
                
                for(int i=s.length()-1;i>=0;i--){
                    if(map.containsKey(s.charAt(i))){
                        if(count<=3){
                            current=map.get(s.charAt(i));
                            if(current>previous){
                                result+=current;
                                count=1;
                            } 
                            if(current==previous){
                                result+=current; 
                                count++;
                            } 
                            if(current<previous){
                                result=result-current;
                                count=1;
                            } 
                        }
                        else
                            return -1;
                    }
                    else
                        return -1;
                        
                    previous=current;
                }
                
                return result;
    }

Log in to reply
 

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