[LeetCode] 524. Longest Word in Dictionary through Deleting

linspiration發表於2019-01-19

Problem

Given a string and a string dictionary, find the longest string in the dictionary that can be formed by deleting some characters of the given string. If there are more than one possible results, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.

Example 1:
Input:
s = “abpcplea”, d = [“ale”,”apple”,”monkey”,”plea”]

Output:
“apple”
Example 2:
Input:
s = “abpcplea”, d = [“a”,”b”,”c”]

Output:
“a”
Note:
All the strings in the input will only contain lower-case letters.
The size of the dictionary won`t exceed 1,000.
The length of all the strings in the input won`t exceed 1,000.

Solution #1 no-sort

class Solution {
    public String findLongestWord(String s, List<String> d) {
        String res = "";
        for (String word: d) {
            if (word.length() > s.length()) continue;
            else {
                int i = 0;
                for (char ch: s.toCharArray()) {
                    if (ch == word.charAt(i)) i++;
                    if (i == word.length()) break;
                }
                if (i == word.length() && word.length() >= res.length()) {
                    if (word.length() > res.length() || word.compareTo(res) < 0) res = word;
                }
            }
        }
        return res;
    }
}

Solution #2 sort first

class Solution {
    public String findLongestWord(String s, List<String> d) {
        if (s == null || d == null || s.length() == 0 || d.size() == 0) return "";
        Collections.sort(d, (a, b)->{
            if (a.length() != b.length()) return b.length()-a.length();
            else return a.compareTo(b);
        });
        for (String word: d) {
            if (s.length() < word.length()) continue;
            //since d is already sorted, 
            //the first one met requirement must be the first longest
            if (isSubseq(s, word)) return word;
        }
        return "";
    }
    private boolean isSubseq(String s, String t) {
        int i = 0, j = 0;
        while (i < s.length() && j < t.length()) {
            if (s.charAt(i) == t.charAt(j)) {
                i++; j++;
            } else i++;
        }
        return j == t.length();
    }
}

相關文章