c++ 哈希表:
将 <字符:数值> 存在 Roman2Int 的哈希表中。
然后从左到右遍历每个字符,如果 s[i] < s[i+1],就将结果减去 s[i] 代表的数字;否则,将结果加上 s[i] 代表的数字。
时间复杂度:
O
(
N
)
O(N)
O(N)。遍历了一遍数组。
空间复杂度:
O
(
1
)
O(1)
O(1)。使用了 Int。
class Solution {
public:
int romanToInt(string s) {
int res=0;
map<char,int> luoma = {
{'I',1},
{'V',5},
{'X',10},
{'L',50},
{'C',100},
{'D',500},
{'M',1000}
}; // 初始化哈希表
for(int i = 0;i<s.length();i++){
if(luoma[s[i]] < luoma[s[i+1]]){
res = res - luoma[s[i]];
}else{
res = res + luoma[s[i]];
}
} //c++11 之后规定,string 末尾会多一个 '\0'字符,所以 s[i+1] 访问到的是 '\0' 字符,也不算越界
// c++ map []取值操作有默认的规则,越界了会返回值初始化的值。
return res;
}
};
python 哈希表
class Solution:
def romanToInt(self, s: str) -> int: # 传入 string s
Roman2Int = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
res = 0;
n = len(s);
for i in range(n-1):
if Roman2Int[s[i]] < Roman2Int[s[i+1]]:
res = res - Roman2Int[s[i]]
else:
res = res + Roman2Int[s[i]]
return res + Roman2Int[s[-1]] # 加上最后一个
c++ 枚举 古典机械式计算器风格:
特殊情况:IV = 4, IX = 9, XL = 40, XC = 90, CD = 400, CM = 900
class Solution {
public:
int romanToInt(string s) {
int res = 0;
int index = 0; // 从头开始遍历字符串
while(index<s.length()){ // 也可以 s.size()
switch(s[index]){
case 'I':
if(s[index+1]=='V'){
res += 4;
index +=2;
break;
}else if(s[index+1]=='X'){
res += 9;
index +=2;
break;
}else{
res += 1;
index++;
break;
}
case 'V':
res += 5;
index++;
break;
case 'X':
if(s[index+1]=='L'){
res += 40;
index +=2;
break;
}else if(s[index+1]=='C'){
res += 90;
index +=2;
break;
}else{
res += 10;
index++;
break;
}
case 'L':
res += 50;
index++;
break;
case 'C':
if(s[index+1]=='D'){
res += 400;
index +=2;
break;
}else if(s[index+1]=='M'){
res += 900;
index +=2;
break;
}else{
res += 100;
index++;
break;
}
case 'D':
res += 500;
index++;
break;
case 'M':
res += 1000;
index++;
break;
}
}
return res;
}
};
哈希表与字典的区别:
字典说的是一种(键)与(值)一一对应的关系,而哈希函数只是众多能帮助我们实现这样的[关系]的工具之一。这样的关系可以用各种方式来表示。比如若要使键有序,则可以将键值对插入到排序树里,若要方便插入,则可以构建一个含键值对的链表。“字典”这个词注重的只是“键”与“值”。
string类中size()、length()和strlen()的区别:
size()、length()是c++中string的类的方法,只有string类的对象才可以用该方法,而字符串数组char不可用,而strlen、strcpy等源于C语言的字符串处理函数库,需要include<string.h>,同时也只有字符串数组char才可以用
详细 string类中size()、length()和strlen()的区别