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:
- 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.
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=='