Ok for me this task is like big head ache.
After analize code Lisa L. from help section in Antony Chalk, I got a little grasp how to do it.
I try do it by mysefl a little simpler and here what we get. (maybe not simpler, but with tools which I knows better, she use streams so ellegantly)
But when I tried validate I got "TIME OUT" "The program ran too long and was closed!".
Maybe you can tell me for start whether algorithm is accurate, and then why it's so robust for memory, and how to slim memory usage.
package com.codegym.task.task22.task2209;
/*
Make a word chain
Okinawa Washington Auckland Kalamazoo Norfolk
Washington Norfolk Kalamazoo Okinawa Auckland
/home/mati/temporary/file4.txt
*/
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Solution {
public static void main(String[] args) throws IOException {
// ...
String fileName = "";
try (BufferedReader nameReader = new BufferedReader(new InputStreamReader(System.in));) {
fileName = nameReader.readLine();
}
String string = "";
try (BufferedReader reader = new BufferedReader(new FileReader(fileName));) {
while (reader.ready()) {
String line = reader.readLine();
string += line;
}
}
String[] words = string.split("\\s+");
System.out.println(getLine(words));
}
// Okinawa Washington Auckland Kalamazoo Norfolk
public static StringBuilder getLine(String... words) {
if (words.length == 0)
return new StringBuilder();
// list for every possible accurate chains
List<String[]> fullList = new ArrayList<>();
for (int i = 0; i < words.length; i++) {
String word = words[i];
List<String> wordsList = new ArrayList<>(Arrays.asList(words));
for (int j = 0; j < wordsList.size(); j++) {
String secondWord = wordsList.get(j);
if (word.equals(secondWord))
continue;
if (!isEqual(word, secondWord))
continue;
word = word + " " + secondWord;
wordsList = new ArrayList<>(Arrays.asList(words));
wordsList.remove(secondWord);
j = -1;
}
fullList.add(word.split("\\s+"));
}
// choose which chains is better
int length = 0;
for (String[] s : fullList) {
if (s.length > length)
length = s.length;
}
for (String[] s : fullList) {
if (s.length == length)
return new StringBuilder(Arrays.toString(s));
}
return new StringBuilder();
}
public static boolean isEqual(String s1, String s2) {
return s1.toLowerCase().charAt(s1.length() - 1) == s2.toLowerCase().charAt(0);
}
}