LeetCode - 13. 羅馬數字轉整數

13. 羅馬數字轉整數

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;

class Solution {

    private static boolean isSpecial(Character a, Character b) {
        if (a.equals('I') && (b.equals('V') || b.equals('X'))) {
            return true;
        }
        if (a.equals('X') && (b.equals('L') || b.equals('C'))) {
            return true;
        }
        if (a.equals('C') && (b.equals('D') || b.equals('M'))) {
            return true;
        }
        return false;
    }

    public static 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);
        Queue<Character> queue = new LinkedList<>();
        char[] chars = s.toCharArray();
        for (int i = 0; i < chars.length; ++ i) {
            queue.add(chars[i]);
        }

        int result = 0;
        while (! queue.isEmpty()) {
            Character one = queue.poll();
            if (! queue.isEmpty()) {
                Character two = queue.peek();
                if (isSpecial(one, two)) {
                    queue.poll();
                    result += map.get(two) - map.get(one);
                    continue;
                }
            }
            result += map.get(one);
        }
        return result;

    }

    public static void main(String[] args) {
        System.out.println(romanToInt("III"));
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章