Skip to content

Instantly share code, notes, and snippets.

@eit
Created October 9, 2015 10:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eit/d122dac52ac3bab0bdd1 to your computer and use it in GitHub Desktop.
Save eit/d122dac52ac3bab0bdd1 to your computer and use it in GitHub Desktop.
class Solution {
public:
bool wordPattern(string pattern, string str) {
vector<string> words = split(str, ' ');
map<char, string> strMap;
map<string, string> checkWord;
if (pattern.length() == 0 || str.length() == 0)
return false;
if (words.size() != pattern.length())
return false;
// pattern mapping str
for(int i=0; i < pattern.size(); i++)
{
if(strMap.find(pattern[i]) != strMap.end())
{
if(strMap[pattern[i]] != words[i])
return false;
}
else
{
if (checkWord.find(words[i]) == checkWord.end())
{
strMap[pattern[i]] = words[i];
checkWord[words[i]] = "";
}
else
return false;
}
}
return true;
}
private:
vector<string> split(const string &s, char delim) {
stringstream ss(s);
string item;
vector<string> tokens;
while (getline(ss, item, delim)) {
tokens.push_back(item);
}
return tokens;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment