290. Word PatternTotal accepted:42115Total submissions:140014 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 was a bijection between a letter in and pattern
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:
Assume contains only pattern
lowercase letters, and contains lowercase letters separated by str
a single space.
Idea: Mapping. Refer to Leetcode 205 for details. The first method of isomorphic strings
Code:
Note the usage of Istringstream, header file <sstream>. This can be used specifically to break down strings that contain spaces .
1 classSolution {2 Public:3 BOOLWordpattern (stringPatternstringstr) {4map<Char,int>P2i;5map<string,int>s2i;6 stringtemp;7 intI=0, n=pattern.size ();8Istringstreaminch(str);9 while(inch>>temp) {Ten if(i<N) { One //there is no corresponding key-value pair in map, 0 is returned A if(p2i[pattern[i]]!=S2i[temp]) { - return false; - } thep2i[pattern[i]]=s2i[temp]=i+1; - } -i++; - } + returni==N; - } +};
Leetcode 290. Word Pattern