@Test public void basicTest() { Assert.assertTrue(PrefixFreeCode.isPrefixFree(new String[]{"01", "10", "0010", "1111"})); Assert.assertFalse(PrefixFreeCode.isPrefixFree(new String[]{"01", "10", "0010", "10100"})); Assert.assertFalse(PrefixFreeCode.isPrefixFree(new String[]{"10100", "01", "10", "0010"})); }
public static boolean isPrefixFree(String[] input) { TrieNode root = new TrieNode(); for (String s : input) { TrieNode p = root; char[] cur = s.toCharArray(); for (int i = 0; i < cur.length; i++) { int key = cur[i] - '0'; if (p.chds[key] == null) { p.chds[key] = new TrieNode(); } p = p.chds[key]; if (p.isEnd) return false; } p.isEnd = true; if (p.chds[0] != null || p.chds[1] != null) return false; } return true; }
PrefixFreeCode { public static boolean isPrefixFree(String[] input) { TrieNode root = new TrieNode(); for (String s : input) { TrieNode p = root; char[] cur = s.toCharArray(); for (int i = 0; i < cur.length; i++) { int key = cur[i] - '0'; if (p.chds[key] == null) { p.chds[key] = new TrieNode(); } p = p.chds[key]; if (p.isEnd) return false; } p.isEnd = true; if (p.chds[0] != null || p.chds[1] != null) return false; } return true; } }
PrefixFreeCode { public static boolean isPrefixFree(String[] input) { TrieNode root = new TrieNode(); for (String s : input) { TrieNode p = root; char[] cur = s.toCharArray(); for (int i = 0; i < cur.length; i++) { int key = cur[i] - '0'; if (p.chds[key] == null) { p.chds[key] = new TrieNode(); } p = p.chds[key]; if (p.isEnd) return false; } p.isEnd = true; if (p.chds[0] != null || p.chds[1] != null) return false; } return true; }  }
PrefixFreeCode { public static boolean isPrefixFree(String[] input) { TrieNode root = new TrieNode(); for (String s : input) { TrieNode p = root; char[] cur = s.toCharArray(); for (int i = 0; i < cur.length; i++) { int key = cur[i] - '0'; if (p.chds[key] == null) { p.chds[key] = new TrieNode(); } p = p.chds[key]; if (p.isEnd) return false; } p.isEnd = true; if (p.chds[0] != null || p.chds[1] != null) return false; } return true; }  static boolean isPrefixFree(String[] input); }
PrefixFreeCode { public static boolean isPrefixFree(String[] input) { TrieNode root = new TrieNode(); for (String s : input) { TrieNode p = root; char[] cur = s.toCharArray(); for (int i = 0; i < cur.length; i++) { int key = cur[i] - '0'; if (p.chds[key] == null) { p.chds[key] = new TrieNode(); } p = p.chds[key]; if (p.isEnd) return false; } p.isEnd = true; if (p.chds[0] != null || p.chds[1] != null) return false; } return true; }  static boolean isPrefixFree(String[] input);  }