[双指针]通过删除字母匹配到字典里最长单词

[双指针]通过删除字母匹配到字典里最长单词_第1张图片

 

class Solution {
    public String findLongestWord(String s, List dictionary) {
        String longWords = "";
        for(String target:dictionary){
            int l1 = longWords.length();int l2 = target.length();
            if(l1>l2 || (l1 == l2 &&longWords.compareTo(target)<0)){
                continue;
            }
            if(isValid(s,target)){
                longWords = target;
            }
        }
        return longWords;
    }
    private boolean isValid(String s,String comapreWord){
        int i = 0;
        int j = 0;
        while ((i < s.length() ) && (j < comapreWord.length() )) {
            char a = s.charAt(i);
            char b = comapreWord.charAt(j);
            if (a == b) {
                i++;
                j++;
                if (j == comapreWord.length() ) {
                    return true;
                }
            } else {
                i++;
            }
        }
        return false;
    }
}

你可能感兴趣的:(leetcode,leetcode)