0 ms C++ solution


  • 6
    A
    class Solution {
    public:
        bool wordPattern(string pattern, string str) {
            map<char, string> m;
            set<string> set_string;
            istringstream input(str);
            string s;
    
            for(int i = 0; i < pattern.size(); i++){
                if(input>>s){
                if(m.find(pattern[i]) != m.end()){
                    if(m[pattern[i]] != s)return false; //pattern already mapped with some other string
                }
                else {
                    if(set_string.count(s)){
                        return false;//string already exist for some pattern char 
                    }
                    else{
                        m[pattern[i]] = s;
                        set_string.insert(s);
                    }
                }
                }
                else return false ;
            }
            if(input>>s)return false ;//more string compared to pattern
            return true;
        }
    };

  • 0
    A

    here test cases are very weak. your code is wrong.
    Try this test case and you will find wrong answer.

    pattern = abbaa
    string= dog cat cat dog

    expected output should be FALSE
    but Output showing is TRUE (from your code)

    Therefore you have missed one condition. Check it. If you cann't find then i will tell you.
    By the way nice solution.


  • 0
    A

    I have updated the solution. Now it runs in 2ms. If any error is left then please bring it to my notice . Thank you.


  • 0
    A

    i have a doubt over expression
    input>>s

    suppose we have string="dog cat cat dog"
    and if write
    for(int i=0;i<7;i++)
    {
    input>>s;
    cout<<s<<endl;
    }

    then o/p will be
    dog
    cat
    cat
    dog
    dog
    dog
    dog

    this means during last string="dog" it is iterating again and again

    then what is the purpose of writing
    if(input>>s) in your code.

    Note: I have just implemented and read first time istringstream there please explain it.


  • 0
    A

    no it will stop after reading 4th dog as there is no string to be read.
    istringstream treat input string as a stream itself, so it is like typing cat dog dog dog by hand and press enter.
    input>>s will then return false , as the stream has failed to read any string after 4 strings


Log in to reply
 

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