码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]13 Roman to Integer

时间:2015-01-02 16:13:57      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:leetcode

https://oj.leetcode.com/problems/roman-to-integer/

http://fisherlei.blogspot.com/2012/12/leetcode-roman-to-integer.html

// Symbol	Value
// I	1
// V	5
// X	10
// L	50
// C	100
// D	500
// M	1,000

public class Solution {
    public int romanToInt(String s) {
        
        Map<Character, Integer> map = new HashMap<>();
        map.put(‘I‘, 1);
        map.put(‘V‘, 5);
        map.put(‘X‘, 10);
        map.put(‘L‘, 50);
        map.put(‘C‘, 100);
        map.put(‘D‘, 500);
        map.put(‘M‘, 1000);
        
        char[] chars = s.toCharArray();

        Character lastChar = null;
        int toReturn = 0;
        for (int i = 0 ; i < chars.length ; i ++)
        {
            char curChar = chars[i];
            int curValue = map.get(curChar);
            Integer lastValue = lastChar == null ? null : map.get(lastChar);
            if (lastValue == null || lastValue >= curValue)
            {
                toReturn += curValue;
            }
            else
            {
                // Last char is wrong
                toReturn -= lastValue;
                toReturn += (curValue - lastValue);
            }
            
            lastChar = curChar;
        }
        
        return toReturn;
    }
}


[LeetCode]13 Roman to Integer

标签:leetcode

原文地址:http://7371901.blog.51cto.com/7361901/1598411

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!