https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/#/solutions
An alternate, more efficient solution which avoids sorting the dictionary: public String findLongestWord(String s, List<String> d) { String longest = ""; // 用来比较的local for (String dictWord : d) { // 题意: 顺序遍历 int i = 0; // 每次都得从target头部开始遍历 for (char c : s.toCharArray()) // 判断字符串的每一个字母相等用toCharArray if (i < dictWord.length() && c == dictWord.charAt(i)) i++; 题意: 比较 if (i == dictWord.length() && dictWord.length() >= longest.length()) //判断是否满足题意 if (dictWord.length() > longest.length() || dictWord.compareTo(longest) < 0) // 是否满足两点, 更新global, 学会s.compareTo(ss) 来比较字典顺序
longest = dictWord; } return longest; } Time Complexity: O(nk), where n is the length of string s and k is the number of words in the dictionary.
时间: 2024-08-26 17:30:28