后缀Trie匹配,匹配操作有问题

如何解决后缀Trie匹配,匹配操作有问题

我遇到了后缀Trie匹配问题,我设计了一个后缀Trie,它具有26路树,用于表示节点中的字符以及与每个节点关联的值。每个节点的值表示在主字符串中字符串(如果为后缀)开头的索引,否则为-1。此后,我试图使匹配操作正常工作,但显然没有,并且我无法在此处找到错误。有关更多说明,请参见Second Question in this Pdf。请帮助。

import java.util.*;

class node{
    public int val;
    public node ptrs[];
    node(){
        this.val =0;
        ptrs = new node[26];
        for (node ptr : ptrs) {
            ptr = null;
        }
    }    
}
class Tree{
    public node root = new node();
    int pass =0;
    void insert(String s,int indx) {
        node trv = root;
        for (int i = 0; i < s.length(); i++) {
            if (trv.ptrs[s.charAt(i) - 'A'] == null) {
                trv.ptrs[s.charAt(i) - 'A'] = new node();
                if(i==s.length()-1){
                    trv.ptrs[s.charAt(i)-'A'].val = indx;
                }else{
                    trv.ptrs[s.charAt(i)-'A'].val = -1;
                }
            }
            trv = trv.ptrs[s.charAt(i) - 'A'];
        }
    }
    
    private void visit(node trv){
        for(int i =0;i<26;i++){
            if(trv.ptrs[i]!=null){
                System.out.println(trv.ptrs[i].val+":"+((char)(i+'A')));
                visit(trv.ptrs[i]);
            }
        }
    }

    void visit(){
        this.visit(root);
    }
    void leaf(node trv){
        if(trv.val>=0){
            System.out.println(trv.val);
        }else{
            for(int i=0;i<26;i++){
                if(trv.ptrs[i]!=null){
                    if(trv.ptrs[i].val>=0){
                        System.out.println(trv.ptrs[i].val);
                    }else{
                        leaf(trv.ptrs[i]);
                    }
                }
            }
        }
    }
    private void search(node trv,String s,int i){
        if(i<=s.length()-1){
            if(trv.ptrs[s.charAt(i)-'A']!=null){
                if(i==s.length()-1){
                    leaf(trv.ptrs[s.charAt(i)-'A']);
                }else{
                    search(trv.ptrs[s.charAt(i)-'A'],s,i+1);
                }
            }
        }
    }
    void query(String s){
        this.search(root,0);
    }
}
public class Trie {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Tree t = new Tree();
        String txt = sc.next();
        int txtLen = txt.length();
        for(int i =0;i<txtLen;i++){
            t.insert(txt.substring(i,txtLen),i);
        }
        int q = sc.nextInt();
        while(q-->0){
           String m = sc.next();
           t.query(m);
        }
        sc.close();
    }
}

预期:

Input:
AATCGGGTTCAATCGGGGT
2
ATCG
GGGT
Output:
1 4 11 15

我的输出:

AATCGGGTTCAATCGGGGT
2
ATCG
11
1
GGGT
4

如您所见,我的答案不是15。

解决方法

我尝试调查您的程序,但是您的程序编写得不好,很遗憾,我找不到您的问题。我尝试通过visit打印它,但是没有有用的信息。

但是以下尝试按Fast Pattern Matching of Strings Using Suffix Tree中所述的后缀树查找模式。也许有帮助:

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

class Node {
    private String text;
    private List<Node> children;
    private int position;

    public Node(String word,int position) {
        this.text = word;
        this.position = position;
        this.children = new ArrayList<>();
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public int getPosition() {
        return position;
    }

    public void setPosition(int position) {
        this.position = position;
    }

    public List<Node> getChildren() {
        return children;
    }

    public void setChildren(List<Node> children) {
        this.children = children;
    }

    public String printTree(String depthIndicator) {
        String str = "";
        String positionStr = position > -1 ? "[" + String.valueOf(position) + "]" : "";
        str += depthIndicator + text + positionStr + "\n";

        for (int i = 0; i < children.size(); i++) {
            str += children.get(i)
                    .printTree(depthIndicator + "\t");
        }
        return str;
    }

    @Override
    public String toString() {
        return printTree("");
    }
}

public class SuffixTree {
    private static final Logger LOGGER = LoggerFactory.getLogger(SuffixTree.class);
    private static final String WORD_TERMINATION = "$";
    private static final int POSITION_UNDEFINED = -1;
    private Node root;
    private String fullText;

    public SuffixTree(String text) {
        root = new Node("",POSITION_UNDEFINED);
        for (int i = 0; i < text.length(); i++) {
            addSuffix(text.substring(i) + WORD_TERMINATION,i);
        }
        fullText = text;
    }

    public List<String> searchText(String pattern) {
        LOGGER.info("Searching for pattern \"{}\"",pattern);
        List<String> result = new ArrayList<>();
        List<Node> nodes = getAllNodesInTraversePath(pattern,root,false);

        if (nodes.size() > 0) {
            Node lastNode = nodes.get(nodes.size() - 1);
            if (lastNode != null) {
                List<Integer> positions = getPositions(lastNode);
                positions = positions.stream()
                        .sorted()
                        .collect(Collectors.toList());
                positions.forEach(m -> result.add((markPatternInText(m,pattern))));
            }
        }
        return result;
    }

    private void addSuffix(String suffix,int position) {
        LOGGER.info(">>>>>>>>>>>> Adding new suffix {}",suffix);
        List<Node> nodes = getAllNodesInTraversePath(suffix,true);
        if (nodes.size() == 0) {
            addChildNode(root,suffix,position);
            LOGGER.info("{}",printTree());
        } else {
            Node lastNode = nodes.remove(nodes.size() - 1);
            String newText = suffix;
            if (nodes.size() > 0) {
                String existingSuffixUptoLastNode = nodes.stream()
                        .map(a -> a.getText())
                        .reduce("",String::concat);

                // Remove prefix from newText already included in parent
                newText = newText.substring(existingSuffixUptoLastNode.length());
            }
            extendNode(lastNode,newText,printTree());
        }
    }

    private List<Integer> getPositions(Node node) {
        List<Integer> positions = new ArrayList<>();
        if (node.getText()
                .endsWith(WORD_TERMINATION)) {
            positions.add(node.getPosition());
        }
        for (int i = 0; i < node.getChildren()
                .size(); i++) {
            positions.addAll(getPositions(node.getChildren()
                    .get(i)));
        }
        return positions;
    }

    private String markPatternInText(Integer startPosition,String pattern) {
        String matchingTextLHS = fullText.substring(0,startPosition);
        String matchingText = fullText.substring(startPosition,startPosition + pattern.length());
        String matchingTextRHS = fullText.substring(startPosition + pattern.length());
        return matchingTextLHS + "[" + matchingText + "]" + matchingTextRHS;
    }

    private void addChildNode(Node parentNode,String text,int position) {
        parentNode.getChildren()
                .add(new Node(text,position));
    }

    private void extendNode(Node node,String newText,int position) {
        String currentText = node.getText();
        String commonPrefix = getLongestCommonPrefix(currentText,newText);

        if (commonPrefix != currentText) {
            String parentText = currentText.substring(0,commonPrefix.length());
            String childText = currentText.substring(commonPrefix.length());
            splitNodeToParentAndChild(node,parentText,childText);
        }

        String remainingText = newText.substring(commonPrefix.length());
        addChildNode(node,remainingText,position);
    }

    private void splitNodeToParentAndChild(Node parentNode,String parentNewText,String childNewText) {
        Node childNode = new Node(childNewText,parentNode.getPosition());

        if (parentNode.getChildren()
                .size() > 0) {
            while (parentNode.getChildren()
                    .size() > 0) {
                childNode.getChildren()
                        .add(parentNode.getChildren()
                                .remove(0));
            }
        }

        parentNode.getChildren()
                .add(childNode);
        parentNode.setText(parentNewText);
        parentNode.setPosition(POSITION_UNDEFINED);
    }

    private String getLongestCommonPrefix(String str1,String str2) {
        int compareLength = Math.min(str1.length(),str2.length());
        for (int i = 0; i < compareLength; i++) {
            if (str1.charAt(i) != str2.charAt(i)) {
                return str1.substring(0,i);
            }
        }
        return str1.substring(0,compareLength);
    }

    private List<Node> getAllNodesInTraversePath(String pattern,Node startNode,boolean isAllowPartialMatch) {
        List<Node> nodes = new ArrayList<>();
        for (int i = 0; i < startNode.getChildren()
                .size(); i++) {
            Node currentNode = startNode.getChildren()
                    .get(i);
            String nodeText = currentNode.getText();
            if (pattern.charAt(0) == nodeText.charAt(0)) {
                if (isAllowPartialMatch && pattern.length() <= nodeText.length()) {
                    nodes.add(currentNode);
                    return nodes;
                }

                int compareLength = Math.min(nodeText.length(),pattern.length());
                for (int j = 1; j < compareLength; j++) {
                    if (pattern.charAt(j) != nodeText.charAt(j)) {
                        if (isAllowPartialMatch) {
                            nodes.add(currentNode);
                        }
                        return nodes;
                    }
                }

                nodes.add(currentNode);
                if (pattern.length() > compareLength) {
                    List<Node> nodes2 = getAllNodesInTraversePath(pattern.substring(compareLength),currentNode,isAllowPartialMatch);
                    if (nodes2.size() > 0) {
                        nodes.addAll(nodes2);
                    } else if (!isAllowPartialMatch) {
                        nodes.add(null);
                    }
                }
                return nodes;
            }
        }
        return nodes;
    }

    public String printTree() {
        return root.printTree("");
    }

    public static void main(String[] args) {
        SuffixTree suffixTree = new SuffixTree("AATCGGGTTCAATCGGGGT");
        List<String> matches = suffixTree.searchText("ATCG");
        matches.stream().forEach(m -> { System.out.println(m);});
        List<String> matches2 = suffixTree.searchText("GGGT");
        matches2.stream().forEach(m -> { System.out.println(m);});
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-