-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution.java
More file actions
50 lines (50 loc) · 1.24 KB
/
solution.java
File metadata and controls
50 lines (50 loc) · 1.24 KB
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
import java.io.*;
import java.lang.*;
import java.util.*;
class HelloWorld {
public static void main(String[] args) throws IOException{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
String[] str=new String[n];
sc.nextLine();
for(int i=0 ; i<n ; i++){
str[i]=sc.nextLine();
}
Arrays.sort(str,Comparator.comparingInt(String::length));
HashMap<String,Integer> map=new HashMap<>();
for(String s:str){
if(map.containsKey(s))
map.put(s,map.get(s)+1);
else map.put(s,1);
}
int count=0;
for(int i=n-1 ; i>=0 ; i--){
StringBuffer sb=new StringBuffer();
int c=0;
for(int j=str[i].length()-1 ; j>=0 ; j--){
sb.append(str[i].charAt(j));
if(map.containsKey(sb.reverse().toString()))
{
if((sb.toString()).equals(str[i]))
continue;
sb.delete(0,sb.length());
c=0;
}
else{
sb.reverse();
c++;
}
}
if(c==0){
count++;
if(count==1)
System.out.println("Longest Compund Word: "+str[i]);
else if(count==2)
System.out.println("Second Longest Compound Word: "+str[i]);
}
System.out.println();
if(count==2)
break;
}
}
}