Hi there,
on the mentor's recommendation, I should try the words in the task description, but I get exactly the same result with them.
If no complete word chain can be formed, an empty StringBuilder is returned - this also corresponds to the sample solution.
Nevertheless the validation does not want to work.
Regards.
package com.codegym.task.task22.task2209;
/*
Make a word chain
*/
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
public class Solution {
public static void main(String[] args) {
String fileName = null;
String[] words;
StringBuilder sb = null;
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
fileName = br.readLine();
} catch (Exception e) {e.printStackTrace();}
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
StringBuilder content = new StringBuilder();
while (br.ready()) content.append(br.readLine()+" ");
words = content.toString().trim().split("\\s+");
sb = getLine(words);
} catch (Exception e) {e.printStackTrace();}
System.out.println(sb);
}
public static StringBuilder getLine(String... words) {
StringBuilder sb = new StringBuilder();
Word.AddWords(words);
boolean start=false, end=false;
while (Word.words.size() > 0) {
Word item = Word.words.get(0);
Word.words.remove(0);
Word prev=Word.getPrevious(item);
Word next=Word.getNext(item);
int offset = sb.length();
if (prev == null) {
if (start) return new StringBuilder();
else {
start = true;
offset = 0;
}
} else if (!Word.words.contains(prev)) {
offset = sb.indexOf(prev.text)+prev.text.length();
}
if (next == null) {
if (end) return new StringBuilder();
else end=true;
} else if (!Word.words.contains(next)) {
offset = sb.indexOf(next.text)-1;
}
sb.insert(offset,(offset == 0 && start) ? item.text : " "+item.text);
}
return sb;
}
private static class Word {
private static ArrayList<Word> init = new ArrayList();
private static ArrayList<Word> words = new ArrayList();
final String text;
final char start, end;
private Word(String text) {
this.text = text;
this.start = text.toLowerCase().charAt(0);
this.end = text.toLowerCase().charAt(text.length()-1);
init.add(this);
words.add(this);
}
public static void AddWords(String... words) {
for (String word : words) new Word(word);
}
public static Word getNext(Word word) {
for (Word w : init) {
if (w == word) continue;
if (word.end == w.start) return w;
}
return null;
}
public static Word getPrevious(Word word) {
for (Word w : init) {
if (w == word) continue;
if (word.start == w.end) return w;
}
return null;
}
public String toString() {return text;}
}
}