【发布时间】:2014-04-02 17:55:41
【问题描述】:
我正在尝试实现PatriciaTrie 数据结构。我最近在通过 Google Docs 进行的编码面试中被问到这个问题。但我无法回答这个问题。
我通过在下面的代码中添加 insert 方法取得了一些进展,但在 PatriciaTrie 代码中的 remove 方法上卡住了 - 不知道如何实现它 -
下面是我的PatriciaTrie 代码-
public class PatriciaTrie {
protected static class Edge {
Node target;
TTString label;
public Edge(Node target, TTString label) {
this.target = target;
this.label = label;
}
}
protected static class Node {
Edge[] edges; // the children of this node
int numberOfChildren; // the number of children
public Node() {
edges = new Edge[128];
numberOfChildren = 0;
}
}
/**
* number of strings stored in the trie
*/
protected int number;
/**
* This is root
*/
protected Node root;
public PatriciaTrie() {
root = new Node();
number = 0;
}
/**
* Add the x to this trie
* @param x the string to add
* @return true if x was successfully added or false if x is already in the trie
*/
public boolean insert(TTString x) {
Node current = root;
for (int i = 0; i < x.length(); i++) {
TTString ch = x.subString(i, 1);
if (current.edges[x.charAt(i)] != null) {
Node child = current.edges[x.charAt(i)].target;
current = child;
} else {
current.edges[x.charAt(i)] = new Edge(new Node(), ch);
current.numberOfChildren++;
current = current.edges[x.charAt(i)].target;
}
if (i == x.length() - 1)
return true;
}
return false;
}
/**
* Remove x from this trie
* @param x the string to remove
* @return true if x was successfully removed or false if x is not stored in the trie
*/
public boolean remove(TTString x) {
// not sure how to do this
return false;
}
}
下面是我的TTString类-
public class TTString {
int i; // index of first character
int m; // length
byte[] data; // data
public TTString(String s) {
data = s.getBytes();
i = 0;
m = s.length();
}
protected TTString(byte[] data, int i, int m) {
this.data = data;
this.i = i;
this.m = m;
}
public TTString subString(int j, int n) {
if (j < 0 || j >= m) throw new IndexOutOfBoundsException();
if (n < 0 || j + n > m) throw new IndexOutOfBoundsException();
return new TTString(data, i+j, n);
}
/**
* The length of this string
* @return
*/
public int length() {
return m;
}
/**
* Return the character at index j
* @param j
* @return
*/
public char charAt(int j) {
return (char)data[i+j];
}
}
关于如何在这里实现remove 方法有什么想法吗?
【问题讨论】:
标签: java algorithm data-structures trie