其他分享
首页 > 其他分享> > Leetcode No.13

Leetcode No.13

作者:互联网

在这里插入图片描述

JS 1°

var romanToInt = function(s) {
    let map = {
         I:1,
         V:5,
         X:10,
         L:50,
         C:100,
         D:500,
         M:1000,
         IV:4,
         IX:9,
         XL:40,
         XC:90,
         CD:400,
         CM:900,
    }
    let result = 0;
    for(let i = 0;i<s.length;){
        if(((i+1)<s.length)&&(map[s.substring(i,i+2)])){
            result = result+map[s.substring(i,i+2)];
            i=i+2;
        }else{
            result = result + map[s.substring(i,i+1)];
            i=i+1
        }
    }
    return result;
};

一开始没头绪,后来还是想到哈希表,然后用笨法两位数优先比较。

python

class Solution:
    def romanToInt(self, s: str) -> int:
        Roman2Int = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
        Int = 0
        n = len(s)

        for index in range(n - 1):
            if Roman2Int[s[index]] < Roman2Int[s[index + 1]]:
                Int -= Roman2Int[s[index]]
            else:
                Int += Roman2Int[s[index]]

        return Int + Roman2Int[s[-1]]

python解法有点玄妙,看了题解。。。

标签:No.13,index,Roman2Int,map,Int,let,result,Leetcode
来源: https://blog.csdn.net/Cloud1209/article/details/113099456