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"

Solution: 先把dict按长度和字母顺序sort(其实不sort也可以),然后对s和词典每个词用two pointers。(substring用two pointers,subsequence用hashmap)

    public String findLongestWord(String s, List<String> d) {
        if (s == null || s.length() == 0 || d == null || d.size() == 0) {
            return "";
        }
        Collections.sort(d, new Comparator<String>() {
            public int compare(String s, String t) {
                if (s.length() != t.length()) {
                    return t.length() - s.length();
                }
                return s.compareTo(t);
            }
        });
        for (String cur : d) {
            int i = 0, j = 0;
            while (i < s.length() && j < cur.length()) {
                if (s.charAt(i) == cur.charAt(j)) {
                    j++;
                }
                i++;
            }
            //注意不是j == cur.length() - 1
            if (j == cur.length()) {
                return cur;
            }
        }
        return "";
    }

results matching ""

    No results matching ""