Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- private:
- long long make_hash(string &s)
- {
- long long hash = 0, p = 1;
- int sz = s.size();
- for (int i = 0; i < sz; i++)
- {
- hash += (s[i] - 'a' + 1) * p;
- p *= 26;
- }
- return hash;
- }
- public:
- bool wordPattern(string pattern, string str) {
- long long dict[26] = {}, h;
- string t;
- int sz1 = pattern.size(), sz2 = str.size(), p1 = 0, p2 = 0;
- while (p1 < sz1)
- {
- while(p2 < sz2 && str[p2] != ' ')
- {
- t.push_back(str[p2]);
- p2++;
- }
- h = make_hash(t);
- t.clear();
- if (!dict[pattern[p1] - 'a'])
- {
- for (int i =0 ; i < 26; ++i)
- if (dict[i] == h)
- return 0;
- dict[pattern[p1] - 'a'] = h;
- }
- else
- if (dict[pattern[p1] - 'a'] != h)
- return 0;
- p1++;
- p2++;
- }
- if (p1 == sz1 && p2 == sz2 + 1)
- return 1;
- return 0;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment