[Java] [Sorting the Dictionary] [Simple] [35ms]


  • 0

    Sort the words in the dictionary according to the following conditions:

    • Longer words come first
    • Words of equal length are sorted lexicographically

    Consider the words in the order they appear in the sorted dictionary. Check if any of the words can be formed by removing character from given string 'S'. In short, just make sure that the characters in the word appear in the same order in both the word and 'S'.

    If no such match exist, return " ".

    public String findLongestWord(String s, List<String> d) {
    	    if(s==null || d==null) return "";
    	    Collections.sort(d,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);
    	        }
    	    });
    	    char[] searchingWord = s.toCharArray();
    	    char[] wordinDictionary;
    	    int i,j;
    	    for(String word: d){
    	        wordinDictionary = word.toCharArray();
    	        j = 0;
    	        i = 0;
    	        while(j<searchingWord.length && i<wordinDictionary.length){
    	            while(j<searchingWord.length && wordinDictionary[i]!=searchingWord[j])j++;
    	            if(j<searchingWord.length && searchingWord[j]==wordinDictionary[i]) i++;
    	            j++;
    	        }
    	        if(i>=wordinDictionary.length) return new String(wordinDictionary);
    	    }
    	    return "";
    }
    

Log in to reply
 

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