LeetCode 524. Longest Word in Dictionary through Deleting (通过删除字母匹配到字典里最长单词)

题目标签:Sort

  对于每一个 字典中的 word, 

    step 1: 先确定它的chars 是不是都出现在s里面。不符合的就不用考虑了。

    step 2: 检查这个word 是否比之前的更长,或者一样长,但是字母顺序更小,是的话需要更新。

Java Solution: 

Runtime:  16ms, faster than 88.86% 

Memory Usage: 40.9, less than 32.54%

完成日期:6/16/2020

关键点:利用 i 来计数 确认 word 的 chars 都出现在s里

class Solution {
    public String findLongestWord(String s, List<String> d) {
        String res = "";
        
        // iterate each word in dictionary
        for(String str : d) {
            int i = 0;
            
            // check each char of word appears in s
            for(char c : s.toCharArray()) {
                if(i < str.length() && c == str.charAt(i))
                    i++;
            }
            
            // check need to save this word
            if(i == str.length() && str.length() >= res.length()) {
                if(str.length() > res.length() || str.compareTo(res) < 0) {
                    res = str;
                }
            }
            
        }
        
        return res;
    }
}

参考资料:https://www.cnblogs.com/grandyang/p/6523344.html

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

原文地址:https://www.cnblogs.com/jimmycheng/p/13151543.html