• I know it is not a good and simple solution, but why it even doesn't work???
I'd like to listen different ideas!Thanks!

``````public class Solution {
public int romanToInt(String s) {
s = s.toUpperCase();
int totalVal = 0;
ArrayList<Integer> al = new ArrayList<Integer>();
for(int i = 0;i < s.length(); i++){
}
for(int i=0; i<al.size()-1;i++)
{
if(al.get(i)>=al.get(i+1))
totalVal = totalVal + al.get(i);
else
totalVal = totalVal - al.get(i);
}
totalVal = totalVal + al.get(al.size()-1);
}
public int toInt(char c){
int returnVal = 0;
switch(c){
case 'I': returnVal = 1;
case 'V': returnVal = 5;
case 'X': returnVal = 10;
case 'L': returnVal = 50;
case 'C': returnVal = 100;
case 'D': returnVal = 500;
case 'M': returnVal = 1000;
}
return returnVal;

}
``````

}

• try to add break statement after each switch condition

• Hi, I have another version based on your idea, but without using arraylist, which means O(1) space complexity.

``````    public int romanToInt(String s) {
if (s == null || s.length() == 0) {
return 0;
}
// directly return the value if the length is 1
if (s.length() == 1) {
return helper(s.charAt(0));
}
// find the first valid index ("--VII")
int index = 0;
while (index < s.length() && helper(s.charAt(index)) == 0) {
index++;
}
// case "--" should return 0
if (index >= s.length()) {
return 0;
}

index = index + 1;
int sum = 0;
int cur = 0, next = 0;

while (index < s.length()) {
cur = helper(s.charAt(index - 1));
next = helper(s.charAt(index));

if (cur < next) {
sum -= cur;
} else {
sum += cur;
}
index++;
}
sum += next;

return sum;
}

private int helper(char ch) {
switch (ch) {
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;
}

return 0;
}
``````

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