Input:
Okinawa Washington Auckland Kalamazoo Norfolk
Output:
Washington Norfolk Kalamazoo Okinawa Auckland
Input:
Okinawa ZZz Washington Zurich Auckland Alexandria Kalamazoo Ottowa Orlando jjj Norfolk
Output:
Washington Norfolk Kalamazoo Orlando Okinawa Alexandria Auckland
It is not the best code in regards of performance, but i can't see why it fails. Maybe someone has another input, with witch my code would fail.
With best regardspackage com.codegym.task.task22.task2209;
/*
Make a word chain
*/
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Solution {
public static void main(String[] args) throws IOException, FileNotFoundException {
// ...
BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));
BufferedReader fileReader = new BufferedReader(new FileReader(consoleReader.readLine()));
consoleReader.close();
String[] arrStr = null;
while(fileReader.ready()) {
arrStr = fileReader.readLine().split(" ");
}
fileReader.close();
StringBuilder result = getLine(arrStr);
System.out.println(result.toString());
}
public static StringBuilder getLine(String... words) {
ArrayList<StringBuilder> test = new ArrayList<StringBuilder>();
if(words.length == 0)
return new StringBuilder();
perm(0, test, words);
StringBuilder max = new StringBuilder();
for(StringBuilder s: test) {
if(s.length() >= max.length())
max = s;
}
return max;
}
public static void perm(int x, ArrayList<StringBuilder> test, String...words) {
if( x == words.length - 1 ) {
test.add(getChain(words));
} else {
for(int i = x; i < words.length; i++) {
swap(words, i, x);
perm(x+1, test, words);
swap(words, x, i);
}
}
}
public static StringBuilder getChain(String[] words) {
StringBuilder sb = new StringBuilder();
for(String s: words) {
if(sb.length() == 0)
sb.append(s);
else if ( sb.charAt(sb.length() -1) == Character.toLowerCase(s.charAt(0))) {
sb.append(" " + s);
} else
break;
}
return sb;
}
public static void swap(String[] words, int x, int y) {
if(x == y)
return;
else {
String temp = words[x];
words[x] = words[y];
words[y] = temp;
}
}
}