可以有两种方式来实现:
前缀树
HashMap
public static void main(String[] args) { String[] listStr={"k","ab","a","kie","kit","kitt","kittty"}; HashMap<String,Integer> map=new HashMap<>(); for(String str:listStr){ map.put(str,1); } PriorityQueue<String> priorityQueue=new PriorityQueue<>((a,b)->b.length()-a.length()); for(String str:listStr){ int endSize=0; for(int i=1;i<=str.length();i++){ String curStr=str.substring(0,i); if(map.containsKey(curStr)){ endSize++; } } if(endSize==str.length()){ priorityQueue.add(str); } } System.out.println(priorityQueue.peek()); }