I was faced with a coding challenge and I'm looking for a more elegant way to achieve the goal.
The challenge
Take the word baseball from the first item in the string array and split it into two comma separated words using only the terms provided in the second item of the string array. If it's impossible to split the word into two separate comma separated words, return the string "not possible".
Example
Given the array new String[] {"baseball","a,all,b,ball,bas,base,cat,code,d,e,quit,z"};
The program should output base,ball
If your program is unable to split baseball using the words from the second item in the string array return "not possible"
I provided the following solution, does anybody have something a little bit more elegant?
public static String ArrayChallenge(String[] strArr) {
//my code starts here
String pattern = strArr[0];
String[] dictionaryWords = strArr[1].split(",");
Set<String> dictionaryWordSet = new HashSet<>(Arrays.asList(dictionaryWords));
String[] tempArr = new String[2];
for (int i = 0; i < pattern.length(); i++) {
String firstWord = pattern.substring(0, i);
if(dictionaryWordSet.contains(firstWord)) {
if(tempArr[0] == null) {
tempArr[0] = firstWord;
} else if(tempArr[0].length() < firstWord.length()) {
tempArr[0] = firstWord;
}
}
String lastWord = pattern.substring(i);
if(dictionaryWordSet.contains(lastWord)) {
tempArr[1] = lastWord;
break;
}
}
if(!pattern.equals(tempArr[0] + tempArr[1])) {
return "not possible";
}
strArr[0] = tempArr[0] + "," + tempArr[1];
//My code ends here
return strArr[0];
}
public static void main(String[] args) {
String[] arr = new String[] {"baseball", "a,all,b,ball,bas,base,cat,code,d,e,quit,z"};
System.out.println(ArrayChallenge(arr));
}