题解 | #牛牛的罗马时代节日#
牛牛的罗马时代节日
https://www.nowcoder.com/practice/97447e046b704ffda3f51281bd7e296b
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param cowsRomanNumeral string字符串一维数组
* @return int整型
*/
public int sumOfRomanNumerals (String[] cowsRomanNumeral) {
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;
}
}
知识点:
字符串处理、哈希表的运用
解题分析:
初始化总和变量sum和当前字符数值变量currentValue。遍历每头牛的罗马数字。对于每个罗马数字字符串,遍历其中的每个字符。在遍历字符时,获取当前字符的数值并存储在currentValue中。
如果当前字符的数值大于前一个字符的数值,则需要减去前一个字符的数值的两倍(因为前一个字符已经被加过一次了)。
将当前字符的数值累加到总和sum中,将前一个字符的数值更新为当前字符的数值,为下一次遍历做准备
编程语言:
java
