tanchukw

Untitled

Oct 23rd, 2015
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.12 KB | None | 0 0
  1. class Solution {
  2. private:
  3. long long make_hash(string &s)
  4. {
  5.     long long hash = 0, p = 1;
  6.     int sz = s.size();
  7.     for (int i = 0; i < sz; i++)
  8.     {
  9.         hash += (s[i] - 'a' + 1) * p;
  10.         p *= 26;
  11.     }
  12.     return hash;
  13. }
  14. public:
  15.     bool wordPattern(string pattern, string str) {
  16.         long long dict[26] = {}, h;
  17.         string t;
  18.         int sz1 = pattern.size(), sz2 = str.size(), p1 = 0, p2 = 0;
  19.         while (p1 < sz1)
  20.         {
  21.             while(p2 < sz2 && str[p2] != ' ')
  22.             {
  23.                 t.push_back(str[p2]);
  24.                 p2++;
  25.             }
  26.             h = make_hash(t);
  27.             t.clear();
  28.             if (!dict[pattern[p1] - 'a'])
  29.             {
  30.                 for (int i =0 ; i < 26; ++i)
  31.                     if (dict[i] == h)
  32.                         return 0;
  33.                 dict[pattern[p1] - 'a'] = h;
  34.             }
  35.             else
  36.                 if (dict[pattern[p1] - 'a'] != h)
  37.                     return 0;
  38.             p1++;
  39.             p2++;
  40.         }
  41.         if (p1 == sz1 && p2 == sz2 + 1)
  42.             return 1;
  43.         return 0;
  44.     }
  45. };
Advertisement
Add Comment
Please, Sign In to add comment