LeetCode 0524. Longest Word in Dictionary through Deleting Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
0524. Longest Word in Dictionary through Deleting

Description

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

 

Example 1:

Input: s = "abpcplea", dictionary = ["ale","apple","monkey","plea"]
Output: "apple"

Example 2:

Input: s = "abpcplea", dictionary = ["a","b","c"]
Output: "a"

 

Constraints:

  • 1 <= s.length <= 1000
  • 1 <= dictionary.length <= 1000
  • 1 <= dictionary[i].length <= 1000
  • s and dictionary[i] consist of lowercase English letters.

Solutions

Solution 1: Subsequence Judgment

We define a function check(s, t) to determine whether string s is a subsequence of string t. We can use a two-pointer approach, initializing two pointers i and j to point to the beginning of strings s and t respectively, then continuously move pointer j. If s[i] equals t[j], then move pointer i. Finally, check if i equals the length of s. If i equals the length of s, it means s is a subsequence of t.

We initialize the answer string ans as an empty string. Then, we iterate through each string t in the array dictionary. If t is a subsequence of s, and the length of t is greater than the length of ans, or the length of t is equal to the length of ans but t is lexicographically smaller than ans, then we update ans to t.

The time complexity is O(d × (m + n)), where d is the length of the string list, and m and n are the lengths of string s and the average length of strings in the list, respectively. The space complexity is O(1).

PythonJavaC++GoTypeScriptRust
class Solution: def findLongestWord(self, s: str, dictionary: List[str]) -> str: def check(s: str, t: str) -> bool: m, n = len(s), len(t) i = j = 0 while i < m and j < n: if s[i] == t[j]: i += 1 j += 1 return i == m ans = "" for t in dictionary: if check(t, s) and (len(ans) < len(t) or (len(ans) == len(t) and ans > t)): ans = t return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !