題目
給定一個字符串數(shù)組兽赁,其中不含有重復字符串掸屡,判斷是否有字符串是另一個字符串的前綴
思路
實現(xiàn)前綴樹即可,判斷是否是前綴樹要么就是我一直在別人的路上走粉洼,要么就是我還沒走完节预,遇到了別人的結尾叶摄。
代碼
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<Character,Tries> children=new HashMap<Character, Tries>();
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);
}
}