Leetcode questions 13 and 14 — Roman numerals to integers, longest common prefix

Time:2021-12-2

1. Leetcode question 13
Requirements: https://leetcode-cn.com/probl…

Important note: usually, the small Roman numerals are to the right of the large ones. But there are also special cases. For example, 4 is not written as IIII, but IV. The number 1 is on the left of the number 5, and the number represented is equal to the value 4 obtained by subtracting the decimal 1 from the large number 5. Similarly, the number 9 is expressed as   IX。 This special rule applies only to the following six cases:
I   Can be placed in   V   (5) And   X   (10) To the left of the, to represent 4 and 9.
X   Can be placed in   L   (50) and   C   To the left of (100) to represent 40 and   90。  
C   Can be placed in   D   (500) and   M   To the left of (1000)   400 and   900。

function print(s) {
    let map = {I: 1,V: 5,X: 10,L: 50,C: 100,D: 500,M: 1000};
    let total = 0;
    for (let i = 0; i < s.length; i++) {
       /*Calculate the total. If the current number is less than the next digit, it means that the above six situations are met. The calculation logic should be to subtract the current digit from the total and then add it
       The latter one is the result we want, such as total = 0; IV=4  0-1+5=4
         */
      total = map[s[i + 1]] && map[s[i]] < map[s[i + 1]]? total - map[s[i]]: total + map[s[i]];
    }
    return total;
  }

2. Leetcode question 14
Requirements: https://leetcode-cn.com/probl…

Write a function to find the longest common prefix in a string array.
Returns the empty string '' if there is no public prefix.

Example 1:
Input: STRs = ["flower", "flow", "flight"]
Output: "FL"

Example 2:
Input: STRs = ["dog", "racecar", "car"]
Output: ''
Explanation: the input does not have a public prefix.
function print(strs) {
    if (strs == null || strs.length == 0) return "";
    for (let i = 0; i < strs[0].length; i++) {
      let char = strs[0][i];
      for (let j = 1; j < strs.length; j++) {
        if (strs[j][i] !== char) return strs[0].substring(0, i);
      }
    }
    return strs[0];
  }