Created
October 9, 2015 10:10
-
-
Save eit/d122dac52ac3bab0bdd1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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