I tried solve this easy leetcode challenge in java. Challenge link
Here is my solution
class Solution {
public int romanToInt(String s) {
Map<String, Integer> data
= new HashMap<String, Integer>() {
{
put("I", 1);
put("V", 5);
put("X", 10);
put("L", 50);
put("C", 100);
put("D", 500);
put("M", 1000);
put("IV", 4);
put("IX", 9);
put("XL", 40);
put("XC", 90);
put("CD", 400);
put("CM", 900);
}
};
String[] edge = {"IV", "IX", "XL", "XC", "CD", "CM"};
int sum = 0;
for (String val : edge) {
if(s.isBlank()) {
break;
} else if(s.contains(val)) {
sum += data.get(val);
int index = s.indexOf(val);
s = s.substring(0, index) + s.substring(index + 2);
}
}
s = s.trim();
for (char c: s.toCharArray()) {
sum += data.get("" + c);
}
return sum;
}
}
I am learning to compute the complexity:
Here is my interpretation
Looks like it is O(6)
constant ~ O(1)
* O(len(string))
~ O(n)
=> O(n)
Correct me if it is not O(n)
Any suggestions on my approach to problem and code where I can reduce time and space complexity.
s.contains(val)
ands.indexOf(val)
have to enumerate through the entire string (and they even get the same result, since.contains()
is roughly speaking.indexOf() != -1
!) and you do both for each edge, ie. 6 times. I am not sure about the complexity of Java's String#substring(), but that might not actually be O(1) either. \$\endgroup\$