import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param cowsRomanNumeral string字符串一维数组 * @return int整型 */ public int sumOfRomanNumerals (String[] cowsRomanNumeral) { // write code here 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); int total = 0; for(int i=0;i<cowsRomanNumeral.length;i++){ total+=totalString(cowsRomanNumeral[i],map); } return total; } public int totalString(String string,Map<Character,Integer> map){ LinkedList<Integer> linkedList = new LinkedList<>(); for(int i=0;i<string.length();i++){ linkedList.add(map.get(string.charAt(i))); } int total = linkedList.get(linkedList.size()-1); for(int i=linkedList.size()-2;i>=0;i--){ if(linkedList.get(i)>=linkedList.get(i + 1)){ total+=linkedList.get(i); }else if(linkedList.get(i)<linkedList.get(i+1)){ total -= linkedList.get(i); } } return total; } }
本题考察的知识点是哈希表的应用,所用编程语言是java.
首先用哈希表存储题目所给的已知条件,然后定义一个函数用来求出每个字符串对应的数值大小,最后对字符串数组中的每个字符串对应的数组进行累加,则求出题目要求答案。
关于求出字符串对应的数值大小,首先我们将字符串的每个字符对应的值按顺序存储在LinkedList当中,然后从左往右或者从右往左判断两个相邻字符对应数值的大小关系,如果相等或者左边的值大于右边则进行累加,如果右边大于左边则右边减去左边,最后得出字符串对应的数值。