My java 90ms solution beats 94% with an int[s.length+1] array reducing extra code for last element and a static int[] hash array for speed up


  • 1
    W
    public class Solution {
        
        private final static int[] trans = {0,0,100,500,0,0,0,0,1,0,0,50,1000,0,0,0,0,0,0,0,0,5,0,10};
        
        public int romanToInt(String s) {
            
            int len = s.length();
            int[] letters = new int[len+1];
            for(int i = 0; i < len; ++i) {
                letters[i] = (trans[s.charAt(i)-'A']);
            }
            int sum = 0;
            for(int i = 0; i < len; ++i) {
                sum = sum + (letters[i]<letters[i+1] ? -letters[i] : +letters[i]);
            }
            return sum;
        }
    }
    

  • 0
    C

    Excellent idea!


Log in to reply
 

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