0ms C++ solution using istringstream and double maps


  • 21
        bool wordPattern(string pattern, string str) {
            istringstream strcin(str);
            string s;
            vector<string> vs;
            while(strcin >> s) vs.push_back(s);
            if (pattern.size() != vs.size()) return false;
            map<string, char> s2c;
            map<char, string> c2s;
            for (int i = 0; i < vs.size(); ++i) {
                if (s2c[vs[i]] == 0 && c2s[pattern[i]] == "") { 
                    s2c[vs[i]] = pattern[i]; 
                    c2s[pattern[i]] = vs[i]; 
                    continue; 
                }
                if (s2c[vs[i]] != pattern[i]) return false;
            }
            return true;
        }

  • 2
    C

    istringstream is quite nice here. And this check if (s2c[vs[i]] != pattern[i]) return false; can be else if (s2c[vs[i]] != pattern[i]) return false;, in order to reduce the comparison.


  • 0
    C

    // Thank you for your inspiration! My solution is basically the same idea as yours but maybe is more easy to understand.

    bool wordPattern(string pattern, string str) {

        istringstream in_str(str);
        string word;
        vector<string> words;
        while (in_str >> word) words.push_back(word);
        if ( words.size() != pattern.size()) return false;
        map<string, char> sc_map;
        map<char, string> cs_map;
        for (int i = 0; i < pattern.size(); ++i) {
            bool check_sc = sc_map.insert(make_pair(words[i], pattern[i])).second;
            bool check_cs = cs_map.insert(make_pair( pattern[i], words[i])).second;
            if (check_sc != check_cs) return false;
        }
        return true;
    }
    

    `


  • 2
    J

    the function "istringstream" is quite cool here. the last one "if (s2c[vs[i]] != pattern[i]) return false;" can be " if (s2c[vs[i]] != pattern[i] || c2s[pattern[i] != vs[i]) return false;", this may be better


  • 0

    not quite agree with you
    continue does the same thing as you said


  • 0
    L

    Thank u so much for providing such a nice solution!


  • 0

    here are some questions

    map<string, char> s2c;
    map<char, string> c2s;
    s2c[vs[i]] == 0 && c2s[pattern[i]] == ""
    

    is the char field of s2c default equal 0?
    is the string field of c2s default equal ""?
    i don't understand?
    i would appreciate if anyone help me with my confusion


  • 0

    @zhangzhiqiangcs Yes, you are right. see this link text.
    for mapped_type& operator[] (const key_type& k) in map, If k does not match the key of any element in the container, the function inserts a new element with that key, the element is constructed using its default constructor.
    and for char type, the default constructor is 0, for string type, it's "".


  • 0

    @ShuangquanLi Thank you


Log in to reply
 

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