1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
| class Solution { private final List<String> ans = new LinkedList<>(); private String target;
public List<String> wordBreak(String s, List<String> wordDict) { if (!quickJudge(s, wordDict)) { return ans; } this.target = s; TreeNode root = new TreeNode("root"); buildTree(s, wordDict, root); for (TreeNode node : root.getChildren()) { dfs(node, ""); } return ans; }
private void dfs(TreeNode root, String str) { if (root.getChildren().size() == 0) { str += root.getVal(); if (str.replaceAll(" ", "").equals(this.target)) { ans.add(str); } return; } else { str += root.getVal() + " "; } for (var node : root.getChildren()) { dfs(node, str); } }
private void buildTree(String s, List<String> dict, TreeNode root) { for (var word : dict) { if (s.startsWith(word)) { TreeNode node = new TreeNode(word); root.getChildren().add(node); int index = word.length(); buildTree(s.substring(index), dict, node); } } }
private boolean quickJudge(String s, List<String> dict) { Set<Character> set = new HashSet<>(); for (String str : dict) { for (char ch : str.toCharArray()) { set.add(ch); } } for (char ch : s.toCharArray()) { if (!set.contains(ch)) { return false; } } return true; } }
class TreeNode { private String val; private final List<TreeNode> children;
public String getVal() { return val; }
public List<TreeNode> getChildren() { return children; }
TreeNode(String x) { children = new LinkedList<>(); val = x; } }
|