Hmm I think alghoritm it's not bad but I'm little tried and maybe I don't see something.
When I put input from my coment result is exact, but when I copy from conditions: Example of file contents
rat tar tart a
a tot tot tot
Result is with some squares, I think it's different format, I try I little combine with StandardCharsets.UTF_8 and getBytes() method but I don't see any difference.
Maybe someone know how to do it.
PS: I know I maybe should spent more time on research, but in other side I don't see when I peek on help site, that anyone do something with setting charsets to UTF-8 (but I only peek).
package com.codegym.task.task22.task2207;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.*;
/*
Inverted words
/home/mati/temporary/file2.txt
rat tar tart a
a tot tot tot rat
tot a tot
OUTPUT:
rat tar
a a
tot tot
tot tot
*/
public class Solution {
public static List<Pair> result = new LinkedList<>();
public static void main(String[] args) throws IOException {
String fileName = "";
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
fileName = reader.readLine();
}
String fullLine = "";
try (BufferedReader fileReader = new BufferedReader(new FileReader(fileName))) {
while (fileReader.ready()) {
int letter = fileReader.read();
fullLine += (char) letter;
}
}
String[] separated = fullLine.split("\\p{Space}");
List <String> listOfWords = new ArrayList<>();
for (String s : separated) {
listOfWords.add(s);
}
for (int i = 0; i < listOfWords.size(); i++) {
String string = listOfWords.get(i);
StringBuilder sb = new StringBuilder(string);
StringBuilder reverse = sb.reverse();
for (int j = i + 1; j < listOfWords.size(); j++) {
if (listOfWords.get(j).equals(reverse.toString())) {
Pair pair = new Pair();
pair.first = string;
pair.second = reverse.toString();
result.add(pair);
listOfWords.remove(i);
listOfWords.remove(j - 1);
break;
}
}
}
// for (String s: listOfWords) {
// System.out.println(s);
// }
// for (Pair pair : result) {
// System.out.println(pair);
// }
}
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;
}
}
}