Leetcode PHP题解--D82 13. Roman to Integer


D82 13. Roman to Integer

题目链接

13. Roman to Integer

题目分析

将给定的罗马数字转换成阿拉伯数字。

思路

用替换法。

要注意,先替换连续出现的那些。例如,比先替换I,要先替换III

最终代码

<?php
class Solution {

    /**
     * @param String $s
     * @return Integer
     */
    function romanToInt($s) {
        $ss = str_replace(['CM','CD','XC','XL','IX','IV','M','D','C','L','X','V','I'],[',900,',',400,',',90,',',40,',',9,',',4,',',1000,',',500,',',100,',',50,',',10,',',5,',',1,'],$s);
        return array_sum(array_filter(explode(',', $ss)));
    }
}

若觉得本文章对你有用,欢迎用爱发电资助。


点赞 取消点赞 收藏 取消收藏

<< 上一篇: Leetcode基础刷题之PHP解析(40. Combination Sum II)

>> 下一篇: Leetcode PHP题解--D83 169. Majority Element