First Thoughts: symbol and value should be connected, meaning we should construct a map of character and integer? It's important to construct the logic of calculating these roman numerals (keyword "after" and "before"). Same character symbol can result in subtraction and addition -> need some logic to differentiate between the two.
My Solution:
public int romanToInt(String s) {
int ret = 0;
HashMap<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);
for (int i=0; i<s.length()-1; i++) {
if (map.get(s.charAt(i))<map.get(s.charAt(i+1)) {
ret -= map.get(s.charAt(i));
}
else ret += map.get(s.charAt(i));
}
ret += map.get(s.charAt(s.length()-1));
return ret;
}
Fully understanding and "codifying" the logic behind the calculation (perhaps trace your thoughts, how you yourself ended up in that answer) is the main key to constructing the solution.
In this case, the crucial point was to differentiate whether the same character meant subtraction or addition -> based on its position (whether the value of the character after is greater / smaller than itself).
Characters themselves don't hold values -> construction of map
Last character always adds to the calculation in roman numerals.