Java Two Point Solution after Sorting the Dictionary


  • 0
    F
    private class MyCompare implements Comparator<String> {
    	public int compare(String s1, String s2) {
    		return s2.length() == s1.length() ? s1.compareTo(s2)
    				: s2.length() - s1.length();
    	}
    }
    
    public String findLongestWord(String s, List<String> d) {
    	Collections.sort(d, new MyCompare());
    	for (String str : d) {
    		if (check(s, str))
    			return str;
    	}
    	return "";
    }
    
    private boolean check(String s1, String s2) {
    	char[] cs1 = s1.toCharArray();
    	char[] cs2 = s2.toCharArray();
    	int i = 0, j = 0;
    	while (i < cs1.length && j < cs2.length) {
    		if (cs1[i] == cs2[j]) 				
    			j++;
    		i++;			
    	}
    	if(j == cs2.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.