# My Accepted Java code 280~310ms

• public class Solution {
private static final Map<Character, Integer> maps = new HashMap<>();
static{
maps.put('I', 1);
maps.put('V', 5);
maps.put('X', 10);
maps.put('L', 50);
maps.put('C', 100);
maps.put('D', 500);
maps.put('M', 1000);
}

public int romanToInt(String s) {
int previousNum = maps.get(s.charAt(0));
int result = maps.get(s.charAt(0));

for (int i = 1; i < s.length(); i++){
if (previousNum < maps.get(s.charAt(i))){
result = result - (2*previousNum);
}

previousNum = maps.get(s.charAt(i));
result += previousNum;
}
return result;
}
}

Not that great performance like another solution because I used HashMap to store key and value instead of count directly. But I think mine can be good for scalable and flexible purpose.

What do you think ? Maybe they will have N for 5000 for example. Just cost one line :3

maps.put('N', 5000);

• public class Problem13 {
public static int romanToInt(String s) {
char[] c = s.toCharArray();
int [] ints = new int[c.length];
int res=0;
for (int i = 0; i < ints.length; i++) {

ints[i]=convert(c[i]);
}
//for (int i = 0; i < ints.length; i++)
int j=0;
while(j<ints.length)
{
if((j+1<ints.length)&&ints[j]<ints[j+1])
{
if(ints[j]==1||ints[j]==10||ints[j]==100){
res=res+ints[j+1]-ints[j];
j+=2;}

}else{
res+=ints[j];
j++;}

}
return res;

}
public static int convert(char c)
{
switch (c) {
case 'I':
return 1;
case 'V':
return 5;
case 'X':
return 10;
case 'L':
return 50;
case 'C':
return 100;
case 'D':
return 500;
case 'M':
return 1000;

default:
return 0;
}

}

}

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.