题目描述
In some cultures, children are named after ancestors and there is a number following which represents how many ancestors have shared that name. They are often shown as Roman Numerals
in Roman numerals, a value ts not repeated more than three times At that point. a smaller value precedes a larger value to indicate subtraction. For example the letter I represents the number 1, and Represents s Reason through the formation of I to 1o below, and see how it is appied in the following lines
样例
For example, f you are given the names [Steven XL, Steven XVI, David IX, Mary XV, Mary XIII, Mary XX]
the result of the sort is (David IX, Mary XIII, Mary XV, Mary XX, Steven XVI, Steven XL)
The resul with Roman numerals is the expected return value.
Written with the numbers in decimal, they are [David 9. Mary 13. Mary I5, Mary 20, Steven 16 Steven 40]
算法1
(字符串处理)
C++ 代码
unordered_map<char, int> words;
string deal(string str)
{
int pos = str.find(' ');
string a1 = str.substr(0, pos);
string a2 = str.substr(pos + 1);
int ans = 0;
for (int i = 0; i < a2.size(); i++)
{
if (i != a2.size() - 1 && words[a2[i + 1]] > words[a2[i]])
{
ans += words[a2[i + 1]] - words[a2[i]];
i++;
}
else
ans += words[a2[i]];
}
return a1 + " " + to_string(ans);
}
vector<string> ancestralNames(vector<string> &names)
{
words['I'] = 1; words['V'] = 5;
words['X'] = 10; words['L'] = 50;
words['C'] = 100; words['D'] = 500;
words['M'] = 1000;
for(int i = 0; i < names.size(); i++)
{
names[i] = deal(names[i]);
}
sort(names.begin(), names.end());
return names;
}