标签:string bre tco length 答案 form nta contains format
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更少。
标签:string bre tco length 答案 form nta contains format
原文地址:https://www.cnblogs.com/chason95/p/10016093.html