Leetcode Roman to integer

Source: Internet
Author: User
class Solution {private:    const static char* pattern[];    const static char* roman[];    unordered_map<string, int> a2i;public:    int romanToInt(string s) {        int res = 0;        if (a2i.size() == 0) build_tlb();                while (!s.empty()) {            int len = s.length();            for (int i=min(4, len); i>0; i--) {                unordered_map<string, int>::iterator iter = a2i.find(s.substr(len-i));                if (iter == a2i.end()) continue;                res += iter->second;                s.resize(len - i);                break;            }        }                return res;    }        void build_tlb() {        int pw = 1;        for (int i=0; i<3; i++) {            for (int j=1; j<=9; j++) {                string rm;                for (int k=0; pattern[j][k] != ‘\0‘; k++) {                    rm.push_back(roman[i][ pattern[j][k] - ‘0‘ ]);                }                a2i.insert(make_pair(rm, pw * j));            }            pw *= 10;        }            a2i.insert(make_pair("M", 1000));        a2i.insert(make_pair("MM", 2000));        a2i.insert(make_pair("MMMM", 3000));    }};const char* Solution::pattern[] = {"A", "0", "00", "000", "01", "1", "10", "100", "1000", "02"};const char* Solution::roman[] = {"IVX", "XLC", "CDM", "M"};

580 MS +, long time

 

If you carefully observe the roman numerals, you can replace each letter with a numerical value and then accumulate them, but there is an exception is to encounter 4, 9 to see a letter before the value of a letter, such as IV if less than the following, the actual corresponding value is V-I = 5-1 = 4, x-I = 10-1 = 9

Specific can refer to: http://www.cnblogs.com/zhuli19901106/p/3453180.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.