An Algorithm a Day: Find the number of letters common in given set of strings
Find the number of letters common in a given set of strings. (Coutesy: HackerRank) Note that the given set of strings might have duplicates.
From the problem statement, i found that since duplicates are there we should remove them and then take the whole set of strings to process the common letters.
Create a set from string, then find common from all sets.
for(int j = 0; j < n ; j++)
{
cout << "Enter string: ";
cin >> str;
RemoveDups(str);
input_strs.push_back(str);
}
cout <<endl<<"Common characters count = ";
cout << GetCommonCharsCount(input_strs);
void RemoveDups(string & str)
{
map<char, bool>visited;
int len = str.length();
for(int i = 0; i < len;)
{
if(visited[str[i]] == true)
{
str.erase(i, 1);
len--;
}
else
{
visited[str[i]] = true;
i++;
}
}
}
int GetCommonCharsCount(vector<string> inputStrs)
{
map<char, unsigned int> charmap;
int count = 0;
for(unsigned int i = 0; i < inputStrs.size(); i++)
{
for(unsigned int j = 0; j < inputStrs[i].length(); j++)
{
charmap[inputStrs[i][j]]++;
}
}
for(map<char, unsigned int>::iterator it = charmap.begin();
it != charmap.end(); it++)
{
if(it->second == inputStrs.size())
count++;
}
return count;
}
Read full article from An Algorithm a Day: Find the number of letters common in given set of strings
Find the number of letters common in a given set of strings. (Coutesy: HackerRank) Note that the given set of strings might have duplicates.
From the problem statement, i found that since duplicates are there we should remove them and then take the whole set of strings to process the common letters.
Create a set from string, then find common from all sets.
for(int j = 0; j < n ; j++)
{
cout << "Enter string: ";
cin >> str;
RemoveDups(str);
input_strs.push_back(str);
}
cout <<endl<<"Common characters count = ";
cout << GetCommonCharsCount(input_strs);
void RemoveDups(string & str)
{
map<char, bool>visited;
int len = str.length();
for(int i = 0; i < len;)
{
if(visited[str[i]] == true)
{
str.erase(i, 1);
len--;
}
else
{
visited[str[i]] = true;
i++;
}
}
}
int GetCommonCharsCount(vector<string> inputStrs)
{
map<char, unsigned int> charmap;
int count = 0;
for(unsigned int i = 0; i < inputStrs.size(); i++)
{
for(unsigned int j = 0; j < inputStrs[i].length(); j++)
{
charmap[inputStrs[i][j]]++;
}
}
for(map<char, unsigned int>::iterator it = charmap.begin();
it != charmap.end(); it++)
{
if(it->second == inputStrs.size())
count++;
}
return count;
}
Read full article from An Algorithm a Day: Find the number of letters common in given set of strings