zoukankan      html  css  js  c++  java
  • 18.8 suffix tree

    给定一个字符串s 和 一个包含较短字符串的数组t,设计一个方法,根据t中的每一个较短的字符换,对s进行搜索。

    思路:基于s建立后缀树,然后在后缀树中进行查找,返回所有可能的索引值。

    import java.util.ArrayList;
    
    public class Question {
        public static void main(String[] args) {
            String testString = "bibs";
            String[] stringList = {"b", "bs", "hi", "bb"};
            SuffixTree tree = new SuffixTree(testString);
            for (String s : stringList) {
                ArrayList<Integer> list = tree.search(s);
                if (list != null) {
                    System.out.println(s + ": " + list.toString());
                }
            }
        }
    }

    /**

    b: [0, 2]

    bs: [2]

    */

     
    import java.util.ArrayList;
    
    public class SuffixTree {
        SuffixTreeNode root = new SuffixTreeNode();
        
        public SuffixTree(String s) {
            for (int i = 0; i < s.length(); i++) {
                String suffix = s.substring(i);
                root.insertString(suffix, i);
            }
        }
        
        public ArrayList<Integer> search(String s) {
            return root.search(s);
        }
    }
    package Question18_8;
    
    import java.util.ArrayList;
    import java.util.HashMap;
    
    public class SuffixTreeNode {
        HashMap<Character, SuffixTreeNode> children = new HashMap<Character, SuffixTreeNode>();
        
        char value;
        ArrayList<Integer> indexes = new ArrayList<Integer>();
        public SuffixTreeNode() { }
        
        public void insertString(String s, int index) {
            indexes.add(index);
            if (s != null && s.length() > 0) {
                value = s.charAt(0);
                SuffixTreeNode child = null;
                if (children.containsKey(value)) {
                    child = children.get(value);
                } else {
                    child = new SuffixTreeNode();
                    children.put(value, child);
                }
                String remainder = s.substring(1);
                child.insertString(remainder, index);
            }
        }
        
        public ArrayList<Integer> search(String s) {
            if (s == null || s.length() == 0) {
                return indexes;
            } else {
                char first = s.charAt(0);
                if (children.containsKey(first)) {
                    String remainder = s.substring(1);
                    return children.get(first).search(remainder);
                }
            }
            return null;
        }
    
    }
  • 相关阅读:
    论 mysql 主键
    详解 hibernate 悲观锁 乐观锁 深入分析 代码实例
    Mysql 如何 删除大表
    JSP 不能用 不支持 STRUTS标签 报错 The Struts dispatcher cannot be found.
    struts2 防止重复提交 实例代码
    ECLIPSE MYECLIPSE 在线安装SVN
    powerdesigner中给一主键设为自增型auto_increment
    GDAL计算栅格图像统计值相关说明
    GDAL使用DEM数据计算坡度坡向
    到底什么是I/O Port,什么是Memorymapped I/O
  • 原文地址:https://www.cnblogs.com/jdflyfly/p/3937499.html
Copyright © 2011-2022 走看看