您的位置:首页 > 其它

LeetCode - 13. 罗马数字转整数

2018-09-08 12:38 513 查看
13. 罗马数字转整数

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;

class Solution {

private static boolean isSpecial(Character a, Character b) {
if (a.equals('I') && (b.equals('V') || b.equals('X'))) {
return true;
}
if (a.equals('X') && (b.equals('L') || b.equals('C'))) {
return true;
}
if (a.equals('C') && (b.equals('D') || b.equals('M'))) {
return true;
}
return false;
}

public static int romanToInt(String s) {
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);
Queue<Character> queue = new LinkedList<>();
char[] chars = s.toCharArray();
for (int i = 0; i < chars.length; ++ i) {
queue.add(chars[i]);
}

int result = 0;
while (! queue.isEmpty()) {
Character one = queue.poll();
if (! queue.isEmpty()) {
Character two = queue.peek();
&nb
b68
sp;            if (isSpecial(one, two)) {
queue.poll();
result += map.get(two) - map.get(one);
continue;
}
}
result += map.get(one);
}
return result;

}

public static void main(String[] args) {
System.out.println(romanToInt("III"));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  简单 罗马 整数