524. Longest Word In Dictionary Through Deleting¶
Difficulty: Medium
LeetCode Problem View on GitHub
524. Longest Word in Dictionary through Deleting
Medium
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 <= 10001 <= dictionary.length <= 10001 <= dictionary[i].length <= 1000sanddictionary[i]consist of lowercase English letters.
Solution¶
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class Solution {
public String findLongestWord(String s, List<String> dictionary) {
int n = s.length();
int flag[] = new int[dictionary.size()];
for (int i = 0; i < dictionary.size(); i++) {
if (canForm(s, dictionary.get(i)))
flag[i] = 1;
}
int maxi = 0;
for (int i = 0; i < dictionary.size(); i++) {
if (flag[i] == 1)
maxi = Math.max(maxi, dictionary.get(i).length());
}
ArrayList<String> res = new ArrayList<>();
for (int i = 0; i < dictionary.size(); i++) {
if (flag[i] == 1 && dictionary.get(i).length() == maxi)
res.add(dictionary.get(i));
}
Collections.sort(res);
if (res.size() == 0)
return "";
return res.get(0);
}
private boolean canForm(String s, String t) {
int n = s.length(), m = t.length();
int i = 0, j = 0;
while (i < n && j < m) {
if (s.charAt(i) == t.charAt(j)) {
i++;
j++;
} else
i++;
}
return j == m;
}
}
Complexity Analysis¶
- Time Complexity:
O(?) - Space Complexity:
O(?)
Approach¶
Detailed explanation of the approach will be added here