?LeetCode刷題實(shí)戰(zhàn)13: 羅馬數(shù)字轉(zhuǎn)整數(shù)
算法的重要性,我就不多說(shuō)了吧,想去大廠,就必須要經(jīng)過(guò)基礎(chǔ)知識(shí)和業(yè)務(wù)邏輯面試+算法面試。所以,為了提高大家的算法能力,這個(gè)公眾號(hào)后續(xù)每天帶大家做一道算法題,題目就從LeetCode上面選 !
今天和大家聊的問(wèn)題叫做羅馬數(shù)字轉(zhuǎn)整數(shù)?,我們先來(lái)看題面:
https://leetcode-cn.com/problems/roman-to-integer/

題意

樣例
示例?1:
輸入:?"III"
輸出:?3
示例?2:
輸入:?"IV"
輸出:?4
示例?3:
輸入:?"IX"
輸出:?9
示例?4:
輸入:?"LVIII"
輸出:?58
解釋: L =?50, V=?5, III =?3.
題解
利用子字符串方法subStrirng拿出兩位字符串,然后在map中查找是否有這個(gè)key,如果有則拿出key鍵所對(duì)應(yīng)的value值,用一個(gè)變量記錄為整數(shù)的值加這個(gè)value值,如果存在兩位的羅馬數(shù)字,則角標(biāo)加2,如果不存在兩位羅馬數(shù)字,即是加1.
public?static?int?romanToInt(String s)?{
????????HashMapmap?= new?HashMap<>();
????????int?result = 0;
????????map.put("I", 1);
????????map.put("IV", 4);
????????map.put("V", 5);
????????map.put("IX", 9);
????????map.put("X", 10);
????????map.put("XL", 40);
????????map.put("L", 50);
????????map.put("XC", 90);
????????map.put("C", 100);
????????map.put("CD", 400);
????????map.put("D", 500);
????????map.put("CM", 900);
????????map.put("M", 1000);
????????for?(int?i = 0; i < s.length(); ) {
????????????if?(i + 1?< s.length() && map.containsKey(s.substring(i, i + 2))) {
????????????????result += map.get(s.substring(i, i + 2));
????????????????i += 2;
????????????} else?{
????????????????result += map.get(""?+ s.charAt(i));
????????????????i++;
????????????}
????????}
????????return?result;
????}
今天的文章就到這里,如果覺(jué)得有所收獲,請(qǐng)順手點(diǎn)個(gè)在看或者轉(zhuǎn)發(fā)吧,你們的支持是我最大的動(dòng)力。
上期推文:
LeetCode刷題實(shí)戰(zhàn)1:在數(shù)組上遍歷出花樣
LeetCode刷題實(shí)戰(zhàn)2:用鏈表模擬加法
LeetCode刷題實(shí)戰(zhàn)3:最長(zhǎng)不重復(fù)子串
LeetCode刷題實(shí)戰(zhàn)4:兩個(gè)正序數(shù)組的中位數(shù)
LeetCode刷題實(shí)戰(zhàn)5:判斷回文子串
LeetCode刷題實(shí)戰(zhàn)6:Z字形變換
LeetCode刷題實(shí)戰(zhàn)7:整數(shù)反轉(zhuǎn)
LeetCode刷題實(shí)戰(zhàn)8:字符串轉(zhuǎn)換整數(shù)
LeetCode刷題實(shí)戰(zhàn)9:求解回文數(shù)
LeetCode刷題實(shí)戰(zhàn)10:字符串正則匹配
LeetCode刷題實(shí)戰(zhàn)11: 盛最多水的容器
LeetCode刷題實(shí)戰(zhàn)12: 整數(shù)轉(zhuǎn)羅馬數(shù)字
