最大的挑战是如何分解输入字符串,所有答案/评论都将基于一些假设,直到 OP 提供更多细节。
在这个答案中,假设输入是首字母大写的驼峰式字符串。
public class CheckDict {
static Set<String> dict = new HashSet<String>(Arrays.asList(new String[]
{"Hi", "Hello", "Welcome", "To", "Stack", "Overflow"}));
public static void main(String[] args) {
System.out.println("Test 1: " + findDict("WelcomeToStackOverflow"));
System.out.println("Test 2: " + findDict("StackOverflowWelcomeYou"));
}
static String findDict(String str) {
// split the string when we encounter an upper case letter except at start
String[] arr = str.split("(?<!^)(?=[A-Z])");
StringBuilder output = new StringBuilder(arr[0]);
for (int i=1; i< arr.length; i++) {
if (!dict.contains(arr[i]))
return null;
else
output.append(' ').append(arr[i]);
}
return output.toString();
}
}
输出:
Test 1: Welcome To Stack Overflow
Test 2: null