18.7 一组字符串里找最长的可以用其他字符串表示的字符串。
用HashMap缓存记录结果,以防止重复计算。
枚举分割点,dfs。
注意单词本身不能由单词本身构成,需要isOrigin符号判断下。
import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; public class Solution { public static String getLongestWord(String[] list) { HashMap<String, Boolean> map = new HashMap<String, Boolean>(); for (String str : list) { map.put(str, true); } Arrays.sort(list, new Comparator<String>() { public int compare(String a, String b) { return ((Integer) b.length()).compareTo(a.length()); } }); for (String each : list) { if (canBuild(map, each, list, true)) return each; } return ""; } private static boolean canBuild(HashMap<String, Boolean> map, String word, String[] list, boolean isOriginWord) { if (map.containsKey(word) && !isOriginWord) return map.get(word); for (int i = 1; i < word.length(); i++) { String left = word.substring(0, i); if (map.containsKey(left) && map.get(left) == true) { if (canBuild(map, word.substring(i), list, false)) return true; } } map.put(word, false); return false; } public static void main(String[] args) { String[] list = { "abc", "bc", "c", "b" }; System.out.println(getLongestWord(list)); } }