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
.spa
Examples:
code
pattern = "abba"
, str = "dog cat cat dog"
should return true.orm
pattern = "abba"
, str = "dog cat cat fish"
should return false.string
pattern = "aaaa"
, str = "dog cat cat dog"
should return false.it
pattern = "abba"
, str = "dog dog dog dog"
should return false.io
四種狀況的測試:class
abba/dog cat cat dog/truestream
abba/dog cat cat fish/falsemap
abba/dog dog dog dog/false
abba/dog cat cat dog dog/false
Code
class Solution { public: bool wordPattern(string pattern, string str) { std::map<char, string> smap; std::set<string> sset; string currentStr; char currentChar; int len = pattern.length(); stringstream strs(str); bool res=true; for(int i=0; i<len; i++) { if(strs.eof()) { res=false; break; } strs>>currentStr; currentChar = pattern[i]; if(smap.find(currentChar) != smap.end()) { if(!(smap[currentChar] == currentStr)) { res=false; break; } } else { if(sset.find(currentStr) == sset.end()) { smap[currentChar] = currentStr; sset.insert(currentStr); } else { res = false; break; } } } if(!strs.eof()) { res=false; } return res; } };