前缀树

题目

给定一个字符串数组,其中不含有重复字符串,判断是否有字符串是另一个字符串的前缀

思路

实现前缀树即可,判断是否是前缀树要么就是我一直在别人的路上走,要么就是我还没走完,遇到了别人的结尾。

代码

import java.util.HashMap;

public class Solution{
    public boolean hasPrefix(String[] strs){
        Tries tries=new Tries();
        for(String str:strs){
            if(tries.AddAndCheck(str.toCharArray(),0))
                return true;
        }
        return false;
    }
}
class Tries {
    HashMap children=new HashMap();
    boolean end=false;
    public boolean AddAndCheck(char[] chars,int i){
        if(end)
            return true;
        if(i==chars.length){
            end=true;
            return !children.isEmpty();
        }
        if(!children.containsKey(chars[i])){
            children.put(chars[i],new Tries());
        }
        return children.get(chars[i]).AddAndCheck(chars,i+1);
    }
}


你可能感兴趣的:(前缀树)