利用trie Tree 解决查找连续子字符串的问题

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Stack;

/**
 * Created by ${chixiu} on 17/11/10.
 */
public class TriedStr {

    public static void main(String[] args) {

        String[] worlds = new String[]{"d","do","dog","p","pe","pen","peng","pengu","pengui","penguin","e","el","ele","elep","eleph","elepha","elephan","elephant"};
        longestWord(worlds);
        System.out.println("TriedStr.main "+longestWord(worlds));
    }

    public static  String longestWord(String[] words) {

        Node root = new Node();
        int i=0;
        for(String sl :words){

            sert( sl, i, root );
            i++;
        }

        return findF(root,words);
    }

    static class Node{

        int index=-1;
        Map<Character,Node> map = new HashMap<Character,Node>();
    }


    public static String findF(Node root,String[] words){

        Node cur = root;
        String ans="";
        Stack<Node>  stack = new Stack<>();

        stack.push(cur);
        while(!stack.empty()){
            Node node = stack.pop();
            if(node == root){
                for( Map.Entry<Character,Node> entrySet:node.map.entrySet()){
                    stack.push(entrySet.getValue());
                }
            }else{
                if(node.index <0){
                    continue;
                }
                String word = words[node.index];
                if (word.length() > ans.length() ||
                        word.length() == ans.length() && word.compareTo(ans) < 0) {
                    ans = word;
                }
                for( Map.Entry<Character,Node> entrySet:node.map.entrySet()){
                    if(entrySet.getValue().index <0){
                        continue;
                    }
                    stack.push(entrySet.getValue());

                }
            }
        }
        return ans;

    }
    public static void  sert(String str,int index,Node root ){

        Node cur = root;
        for(Character character:str.toCharArray()){
            Node node = cur.map.get(character);
            if( node == null){
                node = new Node();
                cur.map.put(character,node);
            }
            cur = node;
        }
        cur.index=index;
    }
}

转载于:https://my.oschina.net/u/1388024/blog/1571193

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值