C++ two maps solution


  • 2
    L
    bool wordPattern(string pattern, string str) {
        // split str by " "
        vector<string> vs;
        istringstream strcin(str);
        string s;
        while (strcin >> s) vs.push_back(s);
        if (pattern.size() != vs.size()) return false;
        
        // The same method of "Isomorphic Strings" by grandyang
        map<char, int> mpc;
        map<string, int> mps;
        for (int i = 0; i < pattern.size(); ++i) {
            if (mpc[pattern[i]] != mps[vs[i]]) return false;
            mpc[pattern[i]] = i + 1;
            mps[vs[i]] = i + 1;
        }
        return true;
    }

  • 1
    M

    Thanks for sharing. I think using std::unordered_map here to replace std::map will also work.


Log in to reply
 

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