最长公共前缀

2019-06-19  本文已影响0人  iamlyly

参考:https://leetcode-cn.com/problems/two-sum/solution/zui-chang-gong-gong-qian-zhui-by-leetcode/

/**

前缀树
public class Trie {
/** Initialize your data structure here. */
private TrieNode root = new TrieNode();

public Trie() {

}

/** Inserts a word into the trie. */
public void insert(String word) {
    char[] chars = word.toCharArray();
    TrieNode cur = root;
    for(char c:chars){
        if(!cur.containsKey(c)){
           TrieNode trieNode= new TrieNode();
           trieNode.setC(c);
            cur.put(c,trieNode);
        }
        cur = cur.get(c);
    }
    cur.setEnd();
}

/** Returns if the word is in the trie. */
public boolean search(String word) {
    char[] chars = word.toCharArray();
    TrieNode cur = root;
    for(char c:chars){
        if(!cur.containsKey(c)){
            return false;
        }
        cur = cur.get(c);
    }
    if(!cur.isEnd) return false;

    return true;
}

/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
    char[] chars = prefix.toCharArray();
    TrieNode cur = root;
    for(char c:chars){
        if(!cur.containsKey(c)){
            return false;
        }
        cur = cur.get(c);
    }

    return true;
}
public String searchLongestPrefix(String word) {
    TrieNode cur = root;
    StringBuffer prefix = new StringBuffer();
    for(int i=0;i<word.length();i++){
        char c = word.charAt(i);
        if(cur.containsKey(c)){
            prefix.append(c);
            cur = cur.get(c);
        }else{
            break;
        }
    }
    return prefix.toString();
}

    class TrieNode{
    private static final int n=26;
    private TrieNode[] nexts=new TrieNode[n];
    private int size=0;
    private boolean isEnd;
    private char c;

        public char getC() {
            return c;
        }

        public void setC(char c) {
            this.c = c;
        }

        public boolean isEnd() {
        return isEnd;
    }

    public void setEnd() {
        isEnd = true;
    }

    public void put(char c, TrieNode node){
        nexts[c-'a']=node;
        size++;
    }
    public int getNextsSize(){
        return size;
    }
    public boolean containsKey(char c){
        return nexts[c-'a']!=null?true:false;
    }
    public TrieNode get(char c) {
        return nexts[c - 'a'];
    }
}

public static void main(String[] args){
    Trie obj = new Trie();
 obj.insert("word");
System.out.println(obj.search("word"));
    System.out.println(obj.startsWith("wo"));
}

}

上一篇 下一篇

猜你喜欢

热点阅读