Share my c++ 0ms solution using maps


  • 1
    L

    Adding the str into a string vector. Then using two maps with same int value, the reason i start with 1 is to avoid when i = 0, adding i = 0 to a value is meaningless.

    class Solution {

    public:

    bool wordPattern(string pattern, string str) {
    
    vector<string> tokens;
    istringstream iss(str);
    unordered_map<char, int> p2i;
    unordered_map<string, int> w2i;
    copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter(tokens));
    
    if (pattern.length() != tokens.size())    return false;
    
    
    for (int i = 1; i < pattern.length() + 1; i++) {
        p2i[pattern[i - 1]] += i;
        w2i[tokens[i - 1]] += i;
        if (p2i[pattern[i - 1]] != w2i[tokens[i - 1]]) {
            return false;
        }
    }
    
    return true;
    
    }
    

    };


  • 0
    W

    Your code is incorrect.
    Bad case:
    "aaaaabccbbbbbba"
    "a a a a a b c c b b b b b b c"


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.