My code works fine with the example, but fails the verification.
I'm wondering about this:
All words passed to the getLine method must be included in the resulting string, if possible.
if not possible (a word not matching the condition) how should I deal with it? I deleted those ones in the result.
package com.codegym.task.task22.task2209;
import java.util.*;
/*
Make a word chain
*/
public class Solution {
public static void main(String[] args) {
// ...
Scanner scanner = new Scanner(System.in);
String line = scanner.nextLine();
String[] words = line.split(" ");
StringBuilder result = getLine(words);
System.out.println(result.toString());
}
public static StringBuilder getLine(String... words) {
StringBuilder sb = new StringBuilder();
LinkedList<Character> first = new LinkedList<>();
LinkedList<Character> last = new LinkedList<>();
LinkedList<String> wl = new LinkedList<>();
ArrayList<String> remove = new ArrayList<>();
for (int i = 0; i < words.length; i++) {
String word = words[i];
first.add(word.toLowerCase().charAt(0));
last.add(word.toLowerCase().charAt(word.length()-1));
wl.add(word);
}
for (Character c : first) {
LinkedList<Character> lastCopy = new LinkedList<>(last);
int index = first.indexOf(c);
LinkedList<Character> firstCopy = new LinkedList<>(first);
firstCopy.remove(index);
lastCopy.remove(index);
if (!lastCopy.contains(c)) {
if (firstCopy.contains(last.get(index))) {
sb.append(wl.get(index));
}
remove.add(wl.get(index));
}
}
wl.removeAll(remove);
while (wl.size() > 0) {
for (String s : wl) {
if (s.toLowerCase().charAt(0) == sb.charAt(sb.length()-1)) {
sb.append(" ");
sb.append(s);
wl.remove(s);
}
}
}
return sb;
}
}