标签:res 数字 get 问题 roman string return length nbsp
双指针问题,当前的数小于后一位,就减去它的值,否则就加上它的值。
class Solution { public int romanToInt(String s) { Map<Character, Integer> demo = new HashMap<>(); demo.put(‘I‘, 1); demo.put(‘V‘, 5); demo.put(‘X‘, 10); demo.put(‘L‘, 50); demo.put(‘C‘, 100); demo.put(‘D‘, 500); demo.put(‘M‘, 1000); int result = 0; for(int i=0;i<s.length()-1;i++){ if(demo.get(s.charAt(i))<demo.get(s.charAt(i+1))){ result -= demo.get(s.charAt(i)); }else{ result += demo.get(s.charAt(i)); } } result += demo.get(s.charAt(s.length()-1)); return result; } }
class Solution: def romanToInt(self, s: str) -> int: demo = {‘I‘:1, ‘V‘:5, ‘X‘:10, ‘L‘:50, ‘C‘:100, ‘D‘:500, ‘M‘:1000} result = 0 for i in range(len(s)-1): if demo[s[i]] < demo[s[i+1]]: result -= demo[s[i]] else: result += demo[s[i]] result += demo[s[len(s)-1]] return result
标签:res 数字 get 问题 roman string return length nbsp
原文地址:https://www.cnblogs.com/huangzengrui/p/12417110.html