zoukankan      html  css  js  c++  java
  • Leetcode: Roman to Integer

    题意

    将罗马字符串转化成对应的数字

    思路

    1. 创建一个hash表, 记录每一个或两个罗马符号对应的数字的值
    2. 对输入的罗马字符串进行匹配. 匹配的时候需要一步lookahead操作, 优先匹配长度为2的罗马符号

    总结

    1. unordered_map<string, int> 不可使用map.find(string[i])操作, 因为string[i] 是一个 char. 正确的操作应当是 map.find(string.substr(2,1))
    2. map 的find操作返回map.end() 或者指向目标pair的指针, 可用 map.find(xx)->first/second 返回pair的值

    代码

      

     1 #include <iostream>
     2 #include <string>
     3 #include <unordered_map>
     4 using namespace std;
     5 int con[13] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
     6 string rom[13] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
     7 unordered_map<string, int> RTI;
     8 class Solution {
     9 public:
    10     int romanToInt(string s) {
    11         // IMPORTANT: Please reset any member data you declared, as
    12         // the same Solution instance will be reused for each test case.
    13         for(int i = 0; i < 13; i ++)
    14             RTI.insert(make_pair(rom[i], con[i]));
    15         int res = 0;
    16         for(int i = 0; i < s.size(); i ++) {
    17             if(i+1<s.size()) {
    18                 string temp = s.substr(i, 2);
    19                 if(RTI.find(temp) != RTI.end()) {
    20                     res += RTI.find(temp)->second;
    21                     i++;
    22                 }else{
    23                     res += RTI.find(s.substr(i,1))->second;
    24                 }
    25             }else{
    26                 res += RTI.find(s.substr(i,1))->second;
    27             }
    28             
    29         }
    30         return res;
    31     }
    32 };
  • 相关阅读:
    python主成分分析
    matplotlib绘图pie
    cpu监控:mpstat命令
    cpu监控:dstat
    MongoDB--安装部署
    Linux-网络管理
    Apache 虚拟主机配置
    Apache 访问控制
    Apache 域名跳转配置
    Apache 日志管理
  • 原文地址:https://www.cnblogs.com/xinsheng/p/3427591.html
Copyright © 2011-2022 走看看