LeetCode刷题——13. 罗马数字转整数(简单)——查表

按顺序做被第4题二分法绊咯半天,做个新手题单压压惊

我的解法:分析对应书写规则(当前数与其右边数对比,若左>=右,则用作加法,否则用作减法),然后查表

但内存消耗偏高,可借鉴下其他写法如用switch替代map

class Solution {
public:
    int romanToInt(string s) {
        map<char,int> excle={{'I',1},{'V',5},{'X',10},{'L',50},{'C',100},{'D',500},{'M',1000}};
        int sum=0;
        for(int i=0;i<s.size()-1;i++){
            if(excle[s[i]]>=excle[s[i+1]]){
                sum+=excle[s[i]];
            }else{
                sum-=excle[s[i]];
            }
        }
        sum+=excle[s[s.size()-1]];

        return sum;
        

    }
};

参考一下题解区大佬Java写法

import java.util.*;

class Solution {
    public int romanToInt(String s) {
        int sum = 0;
        int preNum = getValue(s.charAt(0));
        for(int i = 1;i < s.length(); i ++) {
            int num = getValue(s.charAt(i));
            if(preNum < num) {
                sum -= preNum;
            } else {
                sum += preNum;
            }
            preNum = num;
        }
        sum += preNum;
        return sum;
    }
    
    private int getValue(char ch) {
        switch(ch) {
            case 'I': return 1;
            case 'V': return 5;
            case 'X': return 10;
            case 'L': return 50;
            case 'C': return 100;
            case 'D': return 500;
            case 'M': return 1000;
            default: return 0;
        }
    }
}

作者:donespeak
链接:https://leetcode-cn.com/problems/roman-to-integer/solution/yong-shi-9993nei-cun-9873jian-dan-jie-fa-by-donesp/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

更改后

class Solution {
private:
    int getValue(char ch) {
        switch(ch) {
            case 'I': return 1;
            case 'V': return 5;
            case 'X': return 10;
            case 'L': return 50;
            case 'C': return 100;
            case 'D': return 500;
            case 'M': return 1000;
            default: return 0;
        }
    }
public:
    int romanToInt(string s) {
        int sum=0;
        int pre=getValue(s[0]);
        for(int i=1;i<s.size();i++){
            int now=getValue(s[i]);
            if(pre>=now){
                sum+=pre;
            }else{
                sum-=pre;
            }
            pre=now;
        }
        sum+=pre;

        return sum;
        

    }
};

 总结:在“表”固定且数量较少时,switch语句比map容器更快且减少内存消耗

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值