简体   繁体   中英

How can i compare 2 maps in c++?

(question) Long Pressed Name:

Your friend is typing his name into a keyboard. Sometimes, when typing a character c, the key might get long pressed, and the character will be typed 1 or more times.

You examine the typed characters of the keyboard. Return True if it is possible that it was your friends name, with some characters (possibly none) being long pressed.

My Doubt: : i tried to solve this question with c++ STL maps but i am getting the wrong answer for this test case: name ="saeed"

typed ="ssaaedd"

here is my code:

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;

please help me solving this problem.

This is another way, I tested it and isLongPressedName("s", "sd") correctly yields 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM