Share my accepted Java solution beats 96.7% with explanation:--)


  • 0
    G
    	public static String findLongestWord(String s, List<String> d){
    		String result="";//initial the result
    		for(String K:d){//traverse the dictionary
    			int j=0;//mark, whether finish traversing a dictionary word
    			for(int i=0;i<s.length();i++){
    			    //if s has a letter equals the dictionary word, then move j back
    				if(j<K.length() && s.charAt(i)==K.charAt(j)){
    					j++;
    				}
    			}
    			if(j==K.length()){//if finish traversing the dictionary word
    				if(result!=""){
    					if(K.length()>result.length()){//if find a longer word, reset result
    						result=K;
    					}else if(K.length()==result.length()){ 
    					    //if the word is same length of pre result, compare their lexicographical order
    						result=result.charAt(0)>K.charAt(0)?K:result;
    					}
    				}else{//if nothing contains in the result, reset result
    				    result=K;
    				}
    			}
    		}
    		return result;
    	}

Log in to reply
 

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