FTPrep, 13 Roman to integer
来源:互联网 发布:知乎第一次和女票接吻 编辑:程序博客网 时间:2024/05/22 07:19
于上一题相反,但是套路有变,相同的地方是维护一个table,但这个table只要有7 罗马数字的symbol,重点是:遍历每个字母时,比较它和它左边字母所对应的数字的大小关系,如果是小于等于那就是正常的加法,如果是大于,就是减法。
代码上注意的两点:
1,单个字母的string。string是从右到左遍历。index是右边第二个 len-2 开始,因为len-1提前加了。
2,map的key是字母,而不是string的index,所以:string+index --> key (+ map) --> value
public class Solution { public int romanToInt(String s) { HashMap<Character, Integer> table = new HashMap<>(); table.put('I', 1); table.put('V', 5); table.put('X', 10); table.put('L', 50); table.put('C', 100); table.put('D', 500); table.put('M', 1000); int len=s.length(); int result =0; if(len==1) return table.get(s.charAt(0)); result+=table.get(s.charAt(len-1)); for(int i=len-2; i>=0; --i){ if(table.get(s.charAt(i))<table.get(s.charAt(i+1))) result-=table.get(s.charAt(i)); else result+=table.get(s.charAt(i)); } return result; }}
阅读全文
0 0
- FTPrep, 13 Roman to integer
- FTPrep, 12 Integer to Roman
- 13、Roman to Integer
- 13、Roman to Integer
- 13Roman to Integer
- #13 Roman to Integer
- 13Roman to Integer
- 13 Roman to Integer
- 13 Roman to Integer
- *13 Roman to Integer
- 13、Roman to Integer
- 13 Roman to Integer
- 【13】Roman to Integer
- 13 Roman to Integer
- 13-Roman to Integer
- Leetcode[12-13] Roman to Integer & Integer to Roman(Java)
- LeetCode_OJ【12】【13】Integer to Roman && Roman to Integer
- <LeetCode OJ> 13 / 12 Roman to Integer & Integer to Roman
- Python 操作 Json 基础入门
- android repository中部分support库版本整理
- 洛谷 P1032 字串变换
- 最小化安装centos7要做的几件事情
- 拟阵:贪心原理(bzoj 3105: [cqoi2013]新Nim游戏)
- FTPrep, 13 Roman to integer
- $.ajax()方法详解
- 4123
- 关于数组不得不说的事(二维数组)
- linux之shell字符串截取
- 【二叉树】有序数组建平衡二叉树【108. Convert Sorted Array to Binary Search Tree】
- UE4: Event Dispatcher
- 关于 使用 阿里云 + 宝塔 + wordpress 建站的 心得
- Java小时钟