[LeetCode] Roman to Integer

来源:互联网 发布:台铃t3电动车价格数据 编辑:程序博客网 时间:2024/06/09 23:25

这道和部门内部竞赛出的题目比较类似,而且不用判断异常情况。

public class Solution {    public int romanToInt(String s) {final String[] Roman = { "M", "CM", "D", "CD", "C", "XC", "L", "XL","X", "IX", "V", "IV", "I" };final int[] Value = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5,4, 1 };int[] Counter = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };for (int i = 0, start = 0; i < s.length();) {for (int j = start; j < 13; ++j) {if (s.substring(i).startsWith(Roman[j])) {Counter[j]++;i += Roman[j].length();if (j % 4 == 0) {start = j;} else {// 5, 9, 13start = (j / 4 + 1) * 4 + 1;}start = j;}}}int count = 0;for (int i = 0; i < 13; i++) {count += Value[i] * Counter[i];}return count;            }}


0 0
原创粉丝点击