Advertisement
Guest User

groupanagrams

a guest
Apr 6th, 2020
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.51 KB | None | 0 0
  1. class Solution {
  2. public:
  3. bool isPermute(string str1,string str2)
  4. {
  5.         if(str1.length()==0&&str2.length()==0)
  6.             return true;
  7.         if(str1.length()!=str2.length())
  8.             return false;
  9.         vector<int>s1(26,0);
  10.         vector<int>s2(26,0);
  11.         for(int i=0;i<str1.length();i++)
  12.         {
  13.             s1[((int)str1[i])%26]++;
  14.             s2[((int)str2[i])%26]++;
  15.         }
  16.         for(int i=0;i<s1.size();i++)
  17.         {
  18.             if (s1[i]!=s2[i])
  19.                 return false;
  20.         }
  21.         return true;
  22. }
  23. vector<vector<string> > groupAnagrams(vector<string>& strs) {
  24.         vector<vector<string> > res;
  25.         vector<string> f;
  26.         int i=0;
  27.         while(!strs.empty())
  28.         {
  29.             vector<string>temp;
  30.             temp.push_back(strs[i]);
  31.             int j=i+1;
  32.             while(j<strs.size())
  33.             {
  34.                 while(isPermute(strs[i],strs[j]))
  35.                 {
  36.                     temp.push_back(strs[j]);
  37.                     strs.erase(strs.begin()+j);
  38.                     if (j+1>strs.size())
  39.                         break;
  40.                     if (isPermute(strs[i],strs[j]))
  41.                         continue;
  42.                     else
  43.                         j+=1;
  44.                 }  
  45.                 j+=1;
  46.             }
  47.             if (!temp.empty())
  48.             {
  49.                 res.push_back(temp);
  50.                 temp.clear();
  51.             }
  52.             strs.erase(strs.begin()+i);
  53.         }
  54.         return res;
  55.     }
  56. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement