题解 | #牛牛的罗马时代节日#
牛牛的罗马时代节日
https://www.nowcoder.com/practice/97447e046b704ffda3f51281bd7e296b
知识点
哈希
解题思路
先将字符对应的数字加入到哈希中,遍历数组将将所有的字符串转换为数字相加进ans中。
遍历所有的字符串,如果当前字符对应数字小于上一个字符的数,就直接加上到总和中。如果小于上一个数表示需要减去上一个数,但是上一个数是相加进来的,这一来一去就差了两倍,所以需要减去两倍的上一个数。
Java题解
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param cowsRomanNumeral string字符串一维数组
* @return int整型
*/
public int sumOfRomanNumerals (String[] cowsRomanNumeral) {
// write code here
// 字符对应数放进map
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 ans = 0;
for (String cow : cowsRomanNumeral) {
int value = 0;
for (int i = 0; i < cow.length(); i++) {
int currentValue = map.get(cow.charAt(i));
// 当前数比上一个数大,需要减去上一个数,但上一个数是加进来的,一来一去就差了两倍
if (i > 0 && currentValue > map.get(cow.charAt(i - 1))) {
value += currentValue - 2 * map.get(cow.charAt(i - 1));
} else {
value += currentValue;
}
}
ans += value;
}
return ans;
}
}
查看15道真题和解析