【问题标题】:How can i compare 2 maps in c++?如何在 C++ 中比较 2 个地图?
【发布时间】:2020-05-03 05:35:10
【问题描述】:

(问题)长按姓名:

您的朋友正在用键盘输入他的名字。有时,在键入字符 c 时,可能会长按该键,并且该字符会被键入 1 次或多次。

您检查键盘输入的字符。如果可能是您朋友的名字,则返回 True,其中一些字符(可能没有)被长按。

我的疑问:: 我试图用 C++ STL 映射解决这个问题,但我得到了这个测试用例的错误答案: 名称="saeed"

typed =“ssaaedd”

这是我的代码:

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;

请帮我解决这个问题。

【问题讨论】:

  • 我建议不要为此使用地图。它丢失了有关字符原始顺序的所有信息,因此(例如)它会说 sadeedsa 是相同的,即使它们显然不是。

标签: c++ stl hashmap string-comparison


【解决方案1】:

这是另一种方式,我对其进行了测试,isLongPressedName("s", "sd") 正确地产生了 false。

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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-27
    • 1970-01-01
    • 1970-01-01
    • 2016-01-10
    • 2018-07-17
    • 2014-04-06
    相关资源
    最近更新 更多