13.Roman to integer
int romanToInt(string s) {
int result = ToNum(s[0]);
for(int i = 1; i<s.size();i++)
{
if(ToNum(s[i-1])<ToNum(s[i]))
result +=ToNum(s[i])-2*ToNum(s[i-1]);
else
result +=ToNum(s[i]);
}
return result;
}
int ToNum(char c)
{
//int result;
switch(c){
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;
}
return 0;
}
和前一个比较。
14. longest preflix
terminate called after throwing an instance of 'std::logic_error' what(): basic_string::_M_construct null not valid
对空指针进行操作
string longestCommonPrefix(vector<string>& strs) {
int pos = 0;
int j;
//bool flag = true;
string result;
if(strs.empty())
return result;
if(strs.size() == 1)
return strs[0];
for(pos = 0;pos<strs[0].size();pos++){
for(j = 1;j<strs.size();j++){
if(strs[j][pos] !=strs[j-1][pos]){
//flag = false;
return result;
}
}
result.push_back(strs[0][pos]);
}
return result;
}
循环比较老老实实for循环,push_back better than substr