I can't pass the last condition. Could you give me a hint?
I have tested my code with a file that contains:
tar rat rat tar tart a
a tot tot tot
ab ba ab
c c
d d
and the output was this:
tar rat
a a
tot tot
ab ba
c c
d d
I think I am missing something.
package com.codegym.task.task22.task2207;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
/*
Inverted words
*/
public class Solution {
public static List<Pair> result = new LinkedList<>();
public static void main(String[] args) throws IOException {
BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
String fileName= reader.readLine();
reader.close();
BufferedReader reader1=new BufferedReader(new FileReader(fileName));
ArrayList<String> list=new ArrayList<>();
String data;
while((data= reader1.readLine())!=null){
//I read the line from the file and make it into an array, then adding every element to the list
String []array=data.split(" ");
list.addAll(Arrays.asList(array));
}
reader1.close();
//outer loop. I dont increment the i integer here.
for(int i=0;i<list.size();){
// I create an int initListSize to check if the list size is modified.
int initListSize=list.size();
for(int j=i+1;j< list.size();j++){
//I want to see if the string at list.get(i) is equal to another string in the ArrayList.
String first=list.get(i);
StringBuilder builder=new StringBuilder(list.get(j));
String second=builder.toString();
//If it is equal I create a new Pair() and add it to the result list.
if (first.equals(builder.reverse().toString())) {
Pair pair=new Pair();
pair.first= list.get(i);
pair.second=builder.reverse().toString();
result.add(pair);
//I delete all the matching strings from the list.
while(list.contains(second)||list.contains(first)){
list.remove(first);
list.remove(second);
}
}
}
//Here I check if the list.size() has been modified. If it has been modified there is no need
//to increment i. If the list.size() doesn't modify then we have an element that has no pair and
// we must increment i;
int finalListSize=list.size();
if(initListSize==finalListSize){
i++;
}
}
for(Pair pair:result){
System.out.println(pair.first+" "+pair.second);
}
}
public static class Pair {
String first;
String second;
@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;
}
}
}