Подскажите, что не так? Тестовые примеры проходят. Попробовал разные варианты
package com.javarush.task.task22.task2209;
import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
/*
Составить цепочку слов
*/
public class Solution {
public static void main(String[] args) {
List<String> words = new ArrayList<>();
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in))) {
try (BufferedReader reader = new BufferedReader(new FileReader(bufferedReader.readLine()))) {
String line;
while ((line = reader.readLine()) != null) {
words.addAll(Arrays.asList(line.split(" ")));
}
String[] dublicate = new String[words.size()];
for (int i = 0; i < words.size(); i++) {
dublicate[i] = words.get(i);
}
StringBuilder result = getLine(dublicate);
System.out.println(result.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void sortWords(List<String> copyWords) {
Collections.shuffle(copyWords);
int i;
for (i = 0; i < copyWords.size() - 2; i++) {
int j;
for (j = i + 1; j < copyWords.size(); j++) {
if (copyWords.get(i).charAt(copyWords.get(i).length() - 1) == copyWords.get(j).toLowerCase().charAt(0)) {
String tmp = copyWords.get(i + 1);
copyWords.set(i + 1, copyWords.get(j));
copyWords.set(j, tmp);
break;
}
}
if (j == copyWords.size() - 1 && copyWords.get(i).charAt(copyWords.get(i).length() - 1) != copyWords.get(j).toLowerCase().charAt(0)) {
sortWords(copyWords);
break;
}
}
if (copyWords.get(i).charAt(copyWords.get(i).length() - 1) != copyWords.get(i + 1).toLowerCase().charAt(0)) {
sortWords(copyWords);
}
}
public static StringBuilder getLine(String... words) {
StringBuilder result = new StringBuilder();
List<String> copyWords = new ArrayList<>(Arrays.asList(words));
if (copyWords.isEmpty()) {
return result;
}
sortWords(copyWords);
for (int i = 0; i < copyWords.size(); i++) {
if (i != copyWords.size() - 1) {
result.append(copyWords.get(i)).append(" ");
} else {
result.append(copyWords.get(i));
}
}
return result;
}
}