13. Roman to Integer

class Solution {
    public int romanToInt(String s) {

        Map<String, Integer> hash = new HashMap<>();
        hash.put("I", 1);
        hash.put("V", 5);
        hash.put("X", 10);
        hash.put("L", 50);
        hash.put("C", 100);
        hash.put("D", 500);
        hash.put("M", 1000);
        // MMCDXCVI

        if (s == null || s.length() == 0) return 0;
        int index = s.length() - 2;
        int ans = 0;
        ans += hash.get(s.substring(s.length() - 1));
        while (index >= 0){
            String cur = s.substring(index, index + 1);
            String next = s.substring(index + 1, index + 2);
            if (hash.get(cur) >= hash.get(next)){
                ans += hash.get(cur);
            }
            else{
                ans -= hash.get(cur);
            }
            index--;
        }

        return ans;
    }
}

results for ""

    No results matching ""