Leetcode13 Roman To Integer
Posted chason95
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode13 Roman To Integer相关的知识,希望对你有一定的参考价值。
easy的题,
import java.util.*; public class romanToInteger13 { public int romanToInt(String s) { HashMap<String,Integer> map = new HashMap<>(); int[] values = {1000,900, 500,400,100, 90, 50, 40, 10, 9, 5, 4, 1}; String[] romans = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"}; for(int i=0;i<values.length;i++) map.put(romans[i], values[i]); int ans=0; for(int i=0;i<s.length();i++){ if(i==s.length()-1) {ans+=map.get(s.substring(i));break;} if(map.containsKey(s.substring(i,i+2))) { ans+=map.get(s.substring(i,i+2)); i++; } else { ans+=map.get(s.substring(i,i+1)); } } return ans; } }
43ms,90.62%。
下面是个33ms,100%的答案,思路相近,可以参考。
class Solution { public int value(char r){ if (r == ‘I‘) return 1; if (r == ‘V‘) return 5; if (r == ‘X‘) return 10; if (r == ‘L‘) return 50; if (r == ‘C‘) return 100; if (r == ‘D‘) return 500; if (r == ‘M‘) return 1000; return -1; } public int romanToInt(String s) { int res=0; for(int i=0;i<s.length();i++){ int s1=value(s.charAt(i)); if(i+1<s.length()){ int s2=value(s.charAt(i+1)); if(s1>=s2){ res=res+s1; } else{ res=res+s2-s1; i++; } } else{ res = res + s1; i++; } } return res; } }
它引入的side information更少。
以上是关于Leetcode13 Roman To Integer的主要内容,如果未能解决你的问题,请参考以下文章
#Leetcode# 13. Roman to Integer