I am not sure why this not verifying. Where I am going wrong? Going mad here.
package com.codegym.task.task22.task2207;
import java.io.*;
import java.util.*;
/*
Inverted words
*/
public class Solution {
public static List<Pair> result = new LinkedList<>();
public static void main(String[] args) throws IOException {
BufferedReader b =new BufferedReader(new InputStreamReader(System.in));
BufferedReader bufferedReader = new BufferedReader(new FileReader(b.readLine()));
//BufferedReader bufferedReader = new BufferedReader(new FileReader(xx));
//put all the words in ArrayList
//convert the string into string builder
Map<String, Integer> map = new HashMap<>();
ArrayList<Pair>result = new ArrayList<>();
ArrayList<String>list = new ArrayList<>();
String s;
String[] s2;
while(bufferedReader.ready()) {
s = bufferedReader.readLine();
//each line may contain more than one string
s2 = s.split(" ");
list.addAll(Arrays.asList(s2));
list.remove(" ");
list.remove("");
}
//add each string into list.
for(int i=list.size()-1; i>=0;i--){
//check the String is already in map
if (map.containsKey(list.get(i))) {
map.replace(list.get(i), map.get(list.get(i)) + 1);
}
else {
map.put(list.get(i), 1);
}
}
//now you got arrayList filled with string
//check each array contains pair
for(Map.Entry<String, Integer>pair:map.entrySet()) {
String string =pair.getKey();
StringBuilder sb =new StringBuilder(string);
StringBuilder reverse = new StringBuilder(string);
reverse.reverse(); // now mirror of string created
if(string.equals(reverse.toString()) && map.get(string)>1)//if the word and reverse words are equal like tot / a/dad
{
map.replace(string,0); // to make sure not duplicating
Pair pair1 = new Pair();
pair1.first = string;
pair1.second = reverse.toString();
result.add(pair1);
}
if(map.containsKey(reverse.toString())&&map.get(string)>0){
map.replace(string,0);
map.replace(reverse.toString(),0);
Pair pair1 = new Pair();
pair1.first = string;
pair1.second = reverse.toString();
result.add(pair1);
}
}
//print
for(Pair p:result)
System.out.println(p);
bufferedReader.close();
b.close();
}
public static class Pair {
String first;
String second;
public Pair(){}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair pair = (Pair) o;
if (first != null ? !first.equals(pair.first) : pair.first != null) return false;
return second != null ? second.equals(pair.second) : pair.second == null;
}
@Override
public int hashCode() {
int result = first != null ? first.hashCode() : 0;
result = 31 * result + (second != null ? second.hashCode() : 0);
return result;
}
@Override
public String toString() {
return first == null && second == null ? "" :
first == null ? second :
second == null ? first :
first.compareTo(second) < 0 ? first + " " + second : second + " " + first;
}
}
}