LeetCode.290 - Word Pattern
阿新 • • 發佈:2020-08-22
ummm 我的解決方案記憶體佔用有點大:
class Solution { size_t hash(string s) const { size_t h = 5381; for (auto c : s) h = (h << 5) + h + c; return h; } public: bool wordPattern(string pattern, string str) { str.append(" "); vector<bool> isexist(pattern.size(), false); vector<string> words; string temp; for (auto c : str) { if (c != ' ') temp += c; else { words.push_back(temp); temp.clear(); } } temp.clear(); char* pt = new char[10010](); memset(pt, -1, 10010); int i = 0; for (auto s : words) { size_t pos = hash(s) % 10010; if (i >= pattern.size()) return false; else if (pt[pos] == -1) { if (!isexist[pattern[i] - 'a']) { isexist[pattern[i] - 'a'] = true; pt[pos] = pattern[i++]; } else return false; } else i++; temp += pt[pos]; } delete[] pt; return temp == pattern; } };