leetcode学习记录2.13

[13] 罗马数字转整数

import java.util.HashMap;
import java.util.Map;

/*
 *
 * [13] 罗马数字转整数
 *
 * https://leetcode-cn.com/problems/roman-to-integer/description/
 *
 */

// @lc code=start
class Solution {
    public int romanToInt(String s) {
        Map<String,Integer> map = new HashMap<>();
        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);

        int ans = 0;
        for(int i = 0;i < s.length();){
            if(i + 1 < s.length() && map.containsKey(s.substring(i, i+2)) ){
                ans += map.get(s.substring(i, i+2));
                i += 2;
            }else{
                ans += map.get(s.substring(i,i+1));
                i++;
            }
        }
        return ans;
    }

   
}

str=str.substring(int startIndex);截取掉str从首字母起长度为startIndex的字符串,将剩余字符串赋值给str;

str=str.substring(int startIndex,int endIndex);截取str中从startIndex开始至endIndex结束时的字符串,并将其赋值给str;

在web项目中,有时对数据进行封装处理时,会用到Map和HashMap集合,像Map map = new HashMap()和HashMap hashMap=new HashMap()
1、Map是一个接口,HashMap继承AbstractMap接口和实现了Map接口的类;

2、Map是存储键和值这样的双列数据集合,但存储的数据是没有顺序的,其键不能重复,但其值是可以重复的,可以通过每一个键找到每一个对应的值;HashMap线程不同步的,即线程不安全的,但只有一个线程访问时效率较高;

两者功能相同,不过一般在项目中,HashMap用的比较多些。

posted @ 2022-02-13 17:47  叶梓渔  阅读(38)  评论(0)    收藏  举报