7ms solution in Java. easy to understand


  • 53
    Y
     public int romanToInt(String s) {
        int nums[]=new int[s.length()];
        for(int i=0;i<s.length();i++){
            switch (s.charAt(i)){
                case 'M':
                    nums[i]=1000;
                    break;
                case 'D':
                    nums[i]=500;
                    break;
                case 'C':
                    nums[i]=100;
                    break;
                case 'L':
                    nums[i]=50;
                    break;
                case 'X' :
                    nums[i]=10;
                    break;
                case 'V':
                    nums[i]=5;
                    break;
                case 'I':
                    nums[i]=1;
                    break;
            }
        }
        int sum=0;
        for(int i=0;i<nums.length-1;i++){
            if(nums[i]<nums[i+1])
                sum-=nums[i];
            else
                sum+=nums[i];
        }
        return sum+nums[nums.length-1];
    }

  • 0
    H

    great solution


  • 0
    A

    excellent solution! thanks


  • 3
    P

    @yangneu2015 Time limit exceeds for the case "MMMDLXXXVI"


  • 0
    Q

    @yangneu2015 同学,确定是7ms跑出来的代码???我看了一下记录,Java里面最快也用了80ms。。你是不是在本机上测试用了7ms,或者还是啥情况?因为我之前提交的一版本和你的代码很相似,逻辑基本一致不过我用的是Map,没有使用数组,但是显示Time Limit Exceed。


  • 0
    N

    Excellent! Much better than mine.


  • 0
    H

    Hi :D
    My solution to the problem was the exact same logic but using a hash map to store the letter-value pair, instead of using an array. In fact, my solution only goes through the string once and calculates the sum as it goes through but this solution goes through the same length twice (one for reading string, and one more to go through array) My solution was like 109ms i think.
    Could anyone explain why mine is much slower?


Log in to reply
 

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