13. 罗马数字转整数
https://leetcode-cn.com/problems/roman-to-integer/description/
package com.test; import java.util.HashMap; import java.util.Map; public class Lesson013 { public static void main(String[] args) { String s = "III"; int res = romanToInt(s); System.out.println(res); } private static int romanToInt(String s) { Map<String, Integer> roman = new HashMap<>(8); roman.put("I", 1); roman.put("V", 5); roman.put("X", 10); roman.put("L", 50); roman.put("C", 100); roman.put("D", 500); roman.put("M", 1000); // 特殊情况都遍历了,存到map中 roman.put("IV", 4); roman.put("IX", 9); roman.put("XL", 40); roman.put("XC", 90); roman.put("CD", 400); roman.put("CM", 900); int res = 0; for (int i = 0; i < s.length(); ) { // 取出第i个字符 String c1_str = s.substring(i, i + 1); String c2_str = "a"; // 取出第i+1个字符,注意防止溢出 if (i + 1 < s.length()) { c2_str = s.substring(i + 1, i + 2); } // 取出两个字符 String c12_str = c1_str + c2_str; Integer i1 = roman.get(c1_str); Integer i12 = roman.get(c12_str); // 如果两个字符取出的结果为空,就不是特殊情况 if (i12 == null) { res = res + i1; i = i + 1; } else { res = res + i12; i = i + 2; } } return res; } }