290. Word Pattern

Given a pattern and a string str, find if str follows the same pattern.

Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.

Examples:
pattern = "abba", str = "dog cat cat dog" should return true.
pattern = "abba", str = "dog cat cat fish" should return false.
pattern = "aaaa", str = "dog cat cat dog" should return false.
pattern = "abba", str = "dog dog dog dog" should return false.

Notes: You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.

#include <iostream>
#include <unordered_map>
#include <string>
#include <vector>
#include <sstream>

using namespace std;

bool wordPattern(string pattern, string str){
    if(pattern.empty() && str.empty())    return true;

    if(pattern.empty() || str.empty())    return false;

    vector<string> strArr;
    istringstream istr(str);
    string temp;

    while(istr>>temp)    strArr.push_back(temp);

    if(pattern.size() != strArr.size())    return false;
    unordered_map<char, string> m1;
    unordered_map<string, char> m2;

    for(size_t i = 0; i < pattern.size(); i++){
        if(m1.find(pattern[i]) == m1.end())
            m1[pattern[i]] = strArr[i];
        else if(m1[pattern[i]] != strArr[i])
            return false;

        //这个map是为了   pattern = "abba", str = "dog dog dog dog",如果没有m2,上面将被判为true
        if(m2.find(strArr[i]) != m2.end())
            m2[strArr[i]] = pattern[i];
        else if(m2[ strArr[i]] != pattern[i])
            return false;
    }
    return true;

}

int main(){

    string pattern = "abba";
    string str = "dog dog dog dog";

    if(wordPattern(pattern, str))
        cout<<"true"<<endl;
    else
        cout<<"false"<<endl;
}

results matching ""

    No results matching ""