|
| 1 | +package solutions; |
| 2 | + |
| 3 | +import java.util.List; |
| 4 | + |
| 5 | +// [Problem] https://leetcode.com/problems/longest-word-in-dictionary-through-deleting |
| 6 | +class LongestWordInDictionaryThroughDeleting { |
| 7 | + // Two pointers |
| 8 | + // O(n * l) time, O(1) space |
| 9 | + // where n = number of words in dictionary, l = string length |
| 10 | + public String findLongestWord(String s, List<String> dictionary) { |
| 11 | + String longestWord = ""; |
| 12 | + for (String word : dictionary) { |
| 13 | + if (isValid(s, word) && isLonger(word, longestWord)) { |
| 14 | + longestWord = word; |
| 15 | + } |
| 16 | + } |
| 17 | + return longestWord; |
| 18 | + } |
| 19 | + |
| 20 | + private boolean isValid(String s, String word) { |
| 21 | + int wordIndex = 0; |
| 22 | + for (int i = 0; i < s.length(); i++) { |
| 23 | + if (wordIndex == word.length()) { |
| 24 | + return true; |
| 25 | + } else if (s.charAt(i) == word.charAt(wordIndex)) { |
| 26 | + wordIndex++; |
| 27 | + } |
| 28 | + } |
| 29 | + return wordIndex == word.length(); |
| 30 | + } |
| 31 | + |
| 32 | + private boolean isLonger(String word1, String word2) { |
| 33 | + return word1.length() > word2.length() || (word1.length() == word2.length() && word1.compareTo(word2) < 0); |
| 34 | + } |
| 35 | + |
| 36 | + // Test |
| 37 | + public static void main(String[] args) { |
| 38 | + LongestWordInDictionaryThroughDeleting solution = new LongestWordInDictionaryThroughDeleting(); |
| 39 | + |
| 40 | + String s = "abpcplea"; |
| 41 | + List<String> dictionary = List.of("ale", "apple", "monkey", "plea"); |
| 42 | + String expectedOutput = "apple"; |
| 43 | + String actualOutput = solution.findLongestWord(s, dictionary); |
| 44 | + |
| 45 | + System.out.println("Test passed? " + expectedOutput.equals(actualOutput)); |
| 46 | + } |
| 47 | +} |
0 commit comments