Валидатор ругается на последнее условие. Хотя тестировал на различных вариантах, включая те, которые советуют в комментариях. В чем причина - не пойму
package com.javarush.task.task22.task2209;
/*
Составить цепочку слов
*/
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
String fileName = null;
StringBuilder sb = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
fileName = reader.readLine();
} catch (IOException exc) {
exc.printStackTrace();
}
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
while (reader.ready()) {
sb.append(reader.readLine() + " ");
}
} catch (IOException exc) {
exc.printStackTrace();
}
String[] words = sb.toString().split("\\s");
StringBuilder result = getLine(words);
System.out.println(result.toString());
}
public static StringBuilder getLine(String... words) {
StringBuilder sb = new StringBuilder("");
if (words.length == 0)
return sb;
int temp = 0;
List<String> unsortedList = new ArrayList<>(Arrays.asList(words));
Collections.sort(unsortedList);
sb.append(unsortedList.get(0) + " ");
unsortedList.remove(0);
while (!unsortedList.isEmpty()) {
if (unsortedList.get(0).substring(0, 1).equalsIgnoreCase(sb.substring(sb.length() - 2, sb.length() - 1))) {
sb.append(unsortedList.get(0) + " ");
unsortedList.remove(0);
temp = 0;
} else if (unsortedList.get(0).substring(unsortedList.get(0).length() - 1).equalsIgnoreCase(sb.substring(0, 1))) {
sb.insert(0, unsortedList.get(0) + " ");
unsortedList.remove(0);
temp = 0;
} else if (temp >= unsortedList.size()) {
sb.append(unsortedList.get(0) + " ");
unsortedList.remove(0);
} else {
unsortedList.add(unsortedList.remove(0));
temp++;
}
}
sb.delete(sb.length() - 1, sb.length());
return sb;
}
}