-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathMost_frequent_word_in_an_array_of_strings.java
79 lines (70 loc) · 1.84 KB
/
Most_frequent_word_in_an_array_of_strings.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*
Given an array containing N words, you need to find the most frequent word in the array.
If multiple words have same frequency then print the word that comes first in lexicographical order.
Input:
3
3
geeks for geeks
2
hello world
3
world wide fund
Output:
geeks
hello
fund
*/
/*package whatever //do not write package name here */
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG {
public static void main (String[] args) {
//code
Scanner sc= new Scanner(System.in);
int t= sc.nextInt();
while(t-->0)
{
int len= sc.nextInt();
String[] s= new String[len];
for(int i=0;i<len;i++)
{
s[i]=sc.next();
}
Set<String> a = new HashSet<String>();
HashMap<String,Integer> hmap= new HashMap<String,Integer>();
for(int i=0;i<len;i++)
{
if(a.add(s[i]))
{
hmap.put(s[i],0);
}
}
for(int i=0;i<len;i++)
{
hmap.put(s[i],hmap.get(s[i])+1);
}
StringBuffer res= new StringBuffer("");
int max=0;
for (Map.Entry<String,Integer> entry : hmap.entrySet())
{
// System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
if(entry.getValue()>max)
{
max= entry.getValue();
res= new StringBuffer(entry.getKey());
int polarity=res.toString().compareTo(entry.getKey());
if(polarity<0)
res= new StringBuffer(entry.getKey());
}
if(entry.getValue()==max)
{
int polarity=res.toString().compareTo(entry.getKey());
if(polarity>0)
res= new StringBuffer(entry.getKey());
}
}
System.out.println(res);
}
}
}