Using PriorityQueue to solve this problem!


  • 0
    T
    public class Solution {
        public String findLongestWord(String s, List<String> d) {
             PriorityQueue<String> pq=new PriorityQueue<>(1,new Comparator<String>(){
                     public int compare(String a,String b){
                         if(a.length()!=b.length()){
                             return b.length()-a.length();
                         }else{
                             return a.compareTo(b);
                         }
                     }
             });
             
             
             for(String str:d){
                 pq.offer(str);
             }
             
             while(!pq.isEmpty()){
                 String t=pq.poll();
                 if(issubsequence(s,t)){
                     return t;
                 }
             }
             
             return "";
             
        }
        
        public boolean issubsequence(String a,String b){
            char[] array_a=a.toCharArray();
            char[] array_b=b.toCharArray();
            
            int start=0;
            for(int i=0;i<array_a.length;i++){
                if(array_b[start]==array_a[i]){
                    start++;
                }
                if(start==array_b.length){
                    return true;
                }
            }
            
            return false;
        }
    }
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.