Leetcode_13_Roman to Integer

来源:互联网 发布:java编程实例及讲解 编辑:程序博客网 时间:2024/06/01 08:40

本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/41486885

通过本文你可能学到的知识如下:

    (1)理解本题的解题思路,在以后类似的场景中,如果没有想到比较好的方法,可以考虑使用本文的方法,虽然效率不是特别高。

    (2)能够对字符串的截取和HashMap相关操作有所学习。


Roman to Integer

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

解题思路如下:

    (1)这道题其实不难,可以用switch进行条件判断,并依据返回值累加求得结果。本文使用的是HashMap。

    (2)将罗马数字和对应的整数存储在HashMap中。由于题目限制条件为1—3999,所以需要存储的罗马数字有:1-9、10-100、100-1000、1000-3000,数量其实

不多。

    (3)对于给定的罗马数字字符串,首先,对其长度进行判断,如果长度不为0,则继续。其次,我们发现罗马数字中有很对数字之间具有包含关系,例如III包含II和

I,所以,对于给定的罗马数字字符串,需要判断其子串在Map中对应的值是否为空。我们首先截取第一个字符,判断其在Map中的值是否为空,如果不为空,继续截

取到第二个字符,如果这两个字符在Map中值不为空,我们继续截取到第三个字符,如果这三个字符在Map中值不为空,继续下去......,直到截取到的字符在Map中对

应的值为空,那么将最后添加进去之前的字符对应在Map中的值存储起来,以此类推,直到字符串中所有字符都涉及到截取操作,最后得到的值即为对应的整数的值。



算法实现代码如下所示(PS:本人技术有限,目前还不能写出高效的算法,大家有好的算法希望能够分享,谢谢)

public int romanToInt(String s) {Map<String, Integer> maps = new HashMap<String, Integer>();maps.put("I", 1);maps.put("II", 2);maps.put("III", 3);maps.put("IV", 4);maps.put("V", 5);maps.put("VI", 6);maps.put("VII", 7);maps.put("VIII", 8);maps.put("IX", 9);maps.put("X", 10);maps.put("XX", 20);maps.put("XXX", 30);maps.put("XL", 40);maps.put("L", 50);maps.put("LX", 60);maps.put("LXX", 70);maps.put("LXXX", 80);maps.put("XC", 90);maps.put("C", 100);maps.put("CC", 200);maps.put("CCC", 300);maps.put("CD", 400);maps.put("D", 500);maps.put("DC", 600);maps.put("DCC", 700);maps.put("DCCC", 800);maps.put("CM", 900);maps.put("M", 1000);maps.put("MM", 2000);maps.put("MMM", 3000);if (s.length() == 0)return -1;int count = 0;int flag = 0;for (int i = 0; i < s.length(); i++) {while (flag < s.length()&& maps.get(s.substring(i, flag + 1)) != null) {flag++;}count = count + maps.get(s.substring(i, flag));i = flag - 1;}return count;}


2 0