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
.
Example 1:
Input: pattern ="abba"
, str ="dog cat cat dog"
Output: true
Example 2:
Input:pattern ="abba"
, str ="dog cat cat fish"
Output: false
Example 3:
Input: pattern ="aaaa"
, str ="dog cat cat dog"
Output: false
Example 4:
Input: pattern ="abba"
, str ="dog dog dog dog"
Output: false
Subject to the effect :
Given two strings str pattern and, in accordance with a given rule pattern, determines whether str also follow this rule.
Understanding:
See Example topics will judge misinterpreted as just this pattern is still congruent, this is wrong.
In fact, prior to this topic and a string of characters to replace similar topics. But, here is the word replacement character.
Save with character and word mapping relationship map. With the word save set has been mapped against different characters mapped to the same words.
Str first stored in the word dividing the vector, when the vector length and pattern of unequal size, false is returned.
Traversing pattern, the current character pattern [i] If it is not, it is determined whether there is a corresponding word has occurred is false; otherwise, the map is added to the map.
If the current character pattern [i] has occurred, to determine whether the word corresponding to the current word and the map maps are identical, continue to traverse, otherwise, it returns false.
Code C ++:
class Solution { public: bool wordPattern(string pattern, string str) { Vector < String > splitWords; // divided into words str int the startPos = 0 , blankPos; // record start position of the word, the position of the space String Word; // store word Map < char , String > m; // store two mapping between string Map < char , string > :: Iterator IT; SET < string > m_set; // prevent multiple characters mapped to the same word int I = 0 ; // Traversal while ((blankPos = str.find(' ', startPos))!=str.npos) { Word = str.substr (the startPos, the startPos-blankPos); // start position and length splitWords.push_back (word); round as starting = blankPos + 1 ; } // process the last word IF (the startPos < str.length ()) { word = str.substr(startPos); splitWords.push_back(word); } if (pattern.length() != splitWords.size()) return false; while (pattern[i] != '\0') { it = m.find(pattern[i]); if (it == m.end()) { if (m_set.find(splitWords[i]) == m_set.end()) { m_set.insert(splitWords[i]); } else { return false; } m.insert(pair<char, string>(pattern[i], splitWords[i])); i++; } else { if (strcmp((it->second).c_str(), splitWords[i].c_str()) == 0) in ++ ; else return false ; } } return true; } };
operation result:
When execution: 4 ms, beat the 94.12% of all users to submit in C ++