Word Pattern

Total Accepted: 18003 Total Submissions: 66490 Difficulty: Easy

 

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:

  1. pattern = "abba", str = "dog cat cat dog" should return true.
  2. pattern = "abba", str = "dog cat cat fish" should return false.
  3. pattern = "aaaa", str = "dog cat cat dog" should return false.
  4. 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.

class Solution {
public:
    bool wordPattern(string pattern, string str) {
        unordered_map<char,string> c_str_map;
        unordered_map<string,char> str_c_map;
        istringstream iss(str);
        string word;
        int i=0;
        while(i<pattern.size() && iss>>word ){
            char c = pattern[i++];
            if(i==0){
                c_str_map[c] = word;
                str_c_map[word] = c;
            }else{
                string map_str = c_str_map[c];
                char map_c = str_c_map[word];
                if(map_str == "" && map_c=='\0'){
                    c_str_map[c] = word;
                    str_c_map[word] = c;
                }else if(map_str!=word || map_c!=c){
                    return false;
                }
            }
        }
        if(i==pattern.size() && iss.eof()){
            return true;
        }
        return false;
    }
};
/*
"a"
""

"a"
"word"

"a"
"word word"

"ab"
"word"

"ab"
"word word"

"ab"
"word sek"

"aba"
"word sek word"
*/

 

posted @ 2015-12-16 12:58  zengzy  阅读(267)  评论(0编辑  收藏  举报
levels of contents