高级农民
- 积分
- 1321
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2016-7-6
- 最后登录
- 1970-1-1
|
本帖最后由 lllxin37 于 2021-5-19 10:40 编辑
写delete的时候比想的复杂啊。。。
- // return string begins from start, and the length is len
- public String search(int start, int len) {
- // return value should be between[start, end]
- int end = start + len - 1;
- return searchDfs(start, end, 0, root);
- }
- private String searchDfs(int start, int end, int index, Node curNode) {
- int left = index, right = index + curNode.len - 1;
- if (start > right || end < left) return "";
- // start <= right && end >= left
- if (curNode instanceof Leaf) {
- return ((Leaf) curNode).data
- .substring(Math.max(start, left) - left, Math.min(end, right) + 1 - left);
- }
- String s = "";
- for (Node child : curNode.children) {
- s += searchDfs(start, end, index, child);
- index += child.len;
- }
- return s;
- }
- public void delete(int start, int len) {
- int end = start + len - 1;
- deleteDfs(start, end, 0, root);
- }
- private Node deleteDfs(int start, int end, int index, Node curNode) {
- int left = index, right = index + curNode.len - 1;
- if (start > right || end < left) return curNode;
- // two cases: 1. delete the whole subtree; 2. delete parts of string from curNode to leaf
- int[] toRemove = {Math.max(left, start), Math.min(right, end)};
- int lenToRemove = toRemove[1] - toRemove[0] + 1;
- // whole subtree should be removed;
- if (curNode.len == lenToRemove) {
- return null;
- }
- curNode.len -= lenToRemove;
- if (curNode instanceof Leaf) {
- String leftPart = "", rightPart = "";
- if (left < start) leftPart = ((Leaf) curNode).data.substring(left - left, start - left);
- if (right > end) rightPart = ((Leaf) curNode).data.substring(end + 1 - left, right + 1 - left);
- ((Leaf)curNode).data = leftPart + rightPart;
- return curNode;
- }
- List<Node> newChildren = new ArrayList<>();
- for (Node child : curNode.children) {
- int nextIndex = index + child.len;
- Node newChild = deleteDfs(start, end, index, child);
- if (newChild != null) newChildren.add(newChild);
- index = nextIndex;
- }
- cur.children = newChildren;
- return curNode;
- }
复制代码
|
|