Saturday, November 18, 2017

String - Word Counter

Given a string S as input which consists of multiple words separated by a space, the program must print the count C of the words which are repeated exactly N times. The comparison of the words is case sensitive.

Input Format:
The first line contains S The second line contains N

Output Format:
The first line contains C

Boundary Conditions: 1 <= Length of S <= 10000

Example Input/Output 1:
Input:
one two three four three two five
1
Output:
3
Explanation: The words which are repeated only once are one, four and five. Hence the count is 3.

Solution 1:
a,n=input().split(),int(input())
print(len(set([x for x in a if a.count(x)==n])))

Solution 2:
s,n,c=input().split(),int(input()),0
for i in s:
    if s.count(i)==n:
        c+=1
print(int(c/n))

Solution 3:
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s,a[1000];
int n=-1,m,i=0,l,c=0;
while((cin>>a[++n])>0);
m=atoi(a[--n].c_str());
sort(a,a+n);
while(i<n)
{
l=count(a+i,a+n,a[i]);
i+=l;
if(l==m)
c++;
}
cout<<c;
}
Share: