Leetcode: Roman to Integer
7278 ワード
に言及
ローマ文字列を対応する数字に変換
構想 hashテーブルを作成し、各ローマ記号に対応する数字の値 を記録する.入力ローマ文字列をマッチングする.マッチングにはlookahead操作が必要で、長さ2のローマ記号 を優先的にマッチングします.
まとめ unordered_mapmapは使用できない.find(string[i])はstring[i]がcharであるため動作する.正しい操作はmapであるべきである.find(string.substr(2,1)) 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 };