LeetCode13, Roman numerals are converted to integers

Title description

  1. Roman numerals to integers
    Roman numerals contain the following seven characters: I, V, X, L, C, D and M.

The character value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, the Roman numeral 2 is written as II, which means two parallel 1. 12 is written as XII, which means X + II. 27 is written as XXVII, which is XX + V + II.

Normally, the small numbers in Roman numerals are to the right of the large numbers. But there are special cases, for example, 4 is not written as IIII, but IV. The number 1 is to the left of the number 5, and the number represented is equal to the number 4 obtained by subtracting the number 1 from the large number 5. Similarly, the number 9 is represented as IX. This special rule only applies to the following six situations:

I can be placed to the left of V (5) and X (10) to represent 4 and 9.
X can be placed to the left of L (50) and C (100) to represent 40 and 90.
C can be placed to the left of D (500) and M (1000) to represent 400 and 900.
Given a Roman numeral, convert it to an integer. Ensure that the input is in the range of 1 to 3999.

Example 1:

Input: "III"
Output: 3
Example 2:

Input: "IV"
Output: 4
Example 3:

Input: "IX"
Output: 9
Example 4:

Input: "LVIII"
Output: 58
Explanation: L = 50, V = 5, III = 3.
Example 5:

Input: "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90, IV = 4.

prompt:

The test cases given in the question all comply with the Roman numeral writing rules, and there will be no cross-bits.
Examples such as IC and IM do not meet the requirements of the title. 49 should be written as XLIX, and 999 should be written as CMXCIX.
For detailed rules of writing Roman numerals, please refer to Roman numerals-Mathematics.
Passed 250,382 Submitted 403,078

Direct thinking

As we did last time, that is, to convert integers to Roman numerals, we took advantage of the greedy mind, and each time we found the largest to match. Because its character type is limited.

class Solution {
    
    
    public int romanToInt(String s) {
    
    
        if(s==null||s.length()==0){
    
    
            return 0;
        }
        String [] str = new String[]{
    
    "M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
        int[]nums = new int[]{
    
    1000,900,500,400,100,90,50,40,10,9,5,4,1};
        int start= 0,res=0;
        for(int i=0;i<str.length;i++){
    
    
            int dlt = str[i].length();
            while((start+dlt<=s.length())&&s.substring(start,start+dlt).equals(str[i])){
    
    //需要重复匹配。如MMM的情况
                res+=nums[i];
                start+=dlt;
            }
        }
        return res;

    }
}

Insert picture description here
Complexity analysis:
Time complexity: O(1), because it is a limited operation.
Space complexity: O(1), we all use the space that has been opened up.

Guess you like

Origin blog.csdn.net/qq_44861675/article/details/108437912