Thursday 6 December 2018

Second topmost repeated string in paragraph.

Q. How to find second topmost repeated string in paragraph using any programming language?

ANS:- using HashMap we can store string's as a key and its occurrence as a value and after that we can return highest repeated occurrence as a value. in this video i was given a full explanation of its
working and also find the below code of how to find any occurrence in string using java.



import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map.Entry;

class GetString {
public void getMaxCount(String s) {
String[] arr = s.split(" ");
System.out.println(Arrays.toString(arr));
HashMap<String, Integer> hm = new HashMap<>();
for (String a : arr) {
if (hm.containsKey(a)) {
hm.replace(a, hm.get(a) + 1);
} else {
hm.put(a, 1);
}
}
System.out.println(hm);
Collection<Integer> l = hm.values();
Object []a=l.toArray();

System.out.println(l);
int temp;
for(int i=0;i<a.length;i++) {
for(int j=0;j<a.length-1;j++) {
if((int)a[i]>(int)a[j]) {
temp=(int)a[i];
a[i]=a[j];
a[j]=temp;
}
}
}

System.out.println(Arrays.toString(a));
for(Entry<String, Integer> entry:hm.entrySet()) {
if(entry.getValue()==a[1]) {   // here you can change the index of array according to you.
System.out.println(entry.getKey()+"--->"+entry.getValue());
}
}
}
}

public class SecondString {
public static void main(String[] args) {
String s = "aa bb cc dd aa bb bb bb rr tt rr tt tt tt tt rr rr ww ss ";
GetString gs = new GetString();
gs.getMaxCount(s);

}

}

No comments:

Post a Comment