[LeetCode] Roman to Integer

這道和部門內部競賽出的題目比較類似,而且不用判斷異常情況。

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, 13
						start = (j / 4 + 1) * 4 + 1;
					}
					start = j;
				}
			}
		}
		
		int count = 0;
		for (int i = 0; i < 13; i++) {
			count += Value[i] * Counter[i];
		}

		return count;        
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章