Here Use Hashing Technique.
/*
Input :
Enter Number Of String :: 6
Enter String ::
aubdur
rob
anik
aubdur
rob
anik
Output :
Groups Are ::
Group 1 :
rob
rob
Group 2 :
anik
anik
Group 3 :
aubdur
aubdur
*/
#include<bits/stdc++.h>
#define ll long long int
#define pii pair<ll, int>
#define vector_2D vector<vector<int>>
using namespace std;
ll hash_function(string s)
{
ll p = 31;
ll m = 1e9 + 9;
ll hash_value = 0;
ll p_power = 1;
for(char c : s)
{
hash_value = (hash_value + (c - 'a' + 1) * p_power) % m;
p_power = (p_power * p) % m;
}
return hash_value;
}
vector_2D grouping_string(vector<string> s)
{
int n = s.size();
vector<pii>Hash(n);
for(int i=0;i<n;i++)
Hash[i] = {hash_function(s[i]), i};
sort(Hash.begin(), Hash.end());
vector_2D group;
for(int i=0;i<n;i++)
{
if(i == 0 || Hash[i-1].first != Hash[i].first)
group.emplace_back();
group.back().push_back(Hash[i].second);
}
return group;
}
int main()
{
int n;
cout << "Enter Number Of String :: ";
cin >> n;
vector<string>s(n);
cout << "\nEnter String :: \n";
for(int i=0;i<n;i++)
cin >> s[i];
vector_2D group = grouping_string(s);
cout << "\nGroups Are :: \n";
for(int i=0;i<group.size();i++)
{
cout << "\nGroup " << i+1 << " : \n";
for(int j=0;j<group[i].size();j++)
{
int indx = group[i][j];
cout << s[indx] << "\n";
}
}
return 0;
}
Comments
Post a Comment