[英]How can i compare 2 maps in c++?
你的朋友正在用键盘输入他的名字。 有时,在键入字符 c 时,可能会长按该键,并且该字符将被键入 1 次或多次。
我的疑问::我试图用 c++ STL 地图解决这个问题,但我得到了这个测试用例的错误答案:name =“saeed”
这是我的代码:
bool isLongPressedName(string name, string typed) {
unordered_map<char,int>m1,m2;
for(int i=0;i<name.size();i++)
{
m1[name[i]]++;
}
for(int i=0;i<typed.size();i++)
{
m2[typed[i]]++;
}
if(m2.size()!=m1.size()) return false;
int b=0;
for(int a=0;a<m2.size();a++)
{
if(typed[a]!=name[b] ||m2[typed[a]]<m1[name[b]] )
{
return false;
}
if(m2[typed[a]]>m1[name[b]])
{
return true;
}
b++;
}
return true;
请帮我解决这个问题。
这是另一种方式,我对其进行了测试,并且 isLongPressedName("s", "sd") 正确地产生了错误。
bool isLongPressedName(string name, string typed) {
if (name.size() >= typed.size()) return false;
bool long_pressed = true;
int i = 0, j = 0;
while (i < name.size() && j < typed.size()) {
if (name[i] == typed[j]) {
if (i < name.size() - 1) ++i;
++j;
} else {
if (i > 0 && name[i-1] == typed[j]) {
++j;
} else {
return false;
}
}
}
return long_pressed;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.