LeetCode013——罗马数字转整数

版权声明:版权所有,转载请注明原网址链接。 https://blog.csdn.net/qq_41231926/article/details/82141791

原题链接:https://leetcode-cn.com/problems/roman-to-integer/description/

题目描述:

知识点:数学、字符串

思路:判断I、X、C字符时要判断其下一个字符的字符值

本题是LeetCode12——整数转罗马数字的逆过程。关于LeetCode12——整数转罗马数字的解题,可以参见我的另一篇博文:https://blog.csdn.net/qq_41231926/article/details/82012326

读懂题意,这是关键。对于字符I、X、C我们要判断其后面是否还有字符存在。如果有字符存在,判断后面的字符是什么,我们要结合后面的字符来给I、X、C及其后面如果能结合的字符一起赋值。代码比较长,但是逻辑很简单明了。

时间复杂度是O(n)级别的,其中n为字符串的长度。而空间复杂度,由于方法中使用了一个char型数组来方便操作,空间复杂度也是O(n)级别的。

JAVA代码:

public class Solution {
	
	public int romanToInt(String s) {
		int result = 0;
        char[] array = s.toCharArray();
        for (int i = 0; i < array.length; i++) {
			if(array[i] == 'I') {
				if(i + 1 < array.length && array[i + 1] == 'V') {
					result += 4;
					i++;
				}else if(i + 1 < array.length && array[i + 1] == 'X') {
					result += 9;
					i++;
				}else {
					result += 1;
				}
			}else if(array[i] == 'V') {
				result += 5;
			}else if(array[i] == 'X') {
				if(i + 1 < array.length && array[i + 1] == 'L') {
					result += 40;
					i++;
				}else if(i + 1 < array.length && array[i + 1] == 'C') {
					result += 90;
					i++;
				}else {
					result += 10;
				}
			}else if(array[i] == 'L') {
				result += 50;
			}else if(array[i] == 'C') {
				if(i + 1 < array.length && array[i + 1] == 'D') {
					result += 400;
					i++;
				}else if(i + 1 < array.length && array[i + 1] == 'M') {
					result += 900;
					i++;
				}else {
					result += 100;
				}
			}else if(array[i] == 'D') {
				result += 500;
			}else if(array[i] == 'M') {
				result += 1000;
			}
		}
        return result;
    }
}

LeetCode解题报告:

猜你喜欢

转载自blog.csdn.net/qq_41231926/article/details/82141791