LeetCode #9
What I’ve Learned
First, with one line of code, it can be solved or not. i <s.length() - 1;
Second, To return in String and for appending, we can use StringBuilder.
Disclaimer
My LeetCode is free plan. I am posting just the free algorithms for now on. Also, I am using JAVA to code.
13. Roman to Integer Review
My Solution
I’ve solved it. But the problem was about StringOutOfBoundsException. With one line of code, it can be solved or not. I’ve missed i < s.length() - 1
.
class Solution {
public int romanToInt(String s) {
HashMap<Character, Integer> hash = new HashMap<>();
int sum = 0;
hash.put('I' , 1);
hash.put('V' , 5);
hash.put('X' , 10);
hash.put('L' , 50);
hash.put('C' , 100);
hash.put('D' , 500);
hash.put('M' , 1000);
for(int i =0; i<s.length(); i++) {
if(i<s.length() - 1 && hash.get(s.charAt(i)) < hash.get(s.charAt(i+1))) {
sum += hash.get(s.charAt(i+1)) - hash.get(s.charAt(i));
i++;
}else {
sum += hash.get(s.charAt(i));
}
}
System.out.println(sum);
return sum;
}
}
Solution
This is much faster. By removing i++
statement, it’s time consumption decreases by half.
class Solution {
public int romanToInt(String s) {
HashMap<Character, Integer> hash = new HashMap<>();
int sum = 0;
hash.put('I' , 1);
hash.put('V' , 5);
hash.put('X' , 10);
hash.put('L' , 50);
hash.put('C' , 100);
hash.put('D' , 500);
hash.put('M' , 1000);
for(int i =0; i<s.length(); i++) {
if(i<s.length() - 1 && hash.get(s.charAt(i)) < hash.get(s.charAt(i+1))) {
sum -= hash.get(s.charAt(i));
}else {
sum += hash.get(s.charAt(i));
}
}
System.out.println(sum);
return sum;
}
}
13. Roman to Integer Review
Solution
I wasn’t able to come up with this idea. I keep feeling I am an idiot solving these problems…
class Solution12 {
public void merge(int[] nums1, int m, int[] nums2, int n) {
for (int j = 0, i = m; j < n; j++) {
nums1[i] = nums2[j];
i++;
}
Arrays.sort(nums1);
}
}