Longest Word in Dictionary through Deleting

medium two pointers string

Problem

Given s and a dictionary of words, return the longest word in the dictionary that can be formed by deleting some characters of s. Break ties by lexicographic order; return "" if none qualifies.

Inputs = "abpcplea", words = ["ale","apple","monkey","plea"]
Output"apple"
Both "apple" and "plea" fit; "apple" wins on length, "plea" on lex order — length wins first.

def find_longest_word(s, dictionary):
    best = ""
    for w in dictionary:
        i = 0
        for ch in s:
            if i < len(w) and w[i] == ch:
                i += 1
        if i == len(w):
            if len(w) > len(best) or (len(w) == len(best) and w < best):
                best = w
    return best
function findLongestWord(s, dictionary) {
  let best = "";
  for (const w of dictionary) {
    let i = 0;
    for (const ch of s) {
      if (i < w.length && w[i] === ch) i++;
    }
    if (i === w.length) {
      if (w.length > best.length || (w.length === best.length && w < best)) {
        best = w;
      }
    }
  }
  return best;
}
class Solution {
    public String findLongestWord(String s, List<String> dictionary) {
        String best = "";
        for (String w : dictionary) {
            int i = 0;
            for (int k = 0; k < s.length() && i < w.length(); k++) {
                if (s.charAt(k) == w.charAt(i)) i++;
            }
            if (i == w.length()) {
                if (w.length() > best.length()
                    || (w.length() == best.length() && w.compareTo(best) < 0)) {
                    best = w;
                }
            }
        }
        return best;
    }
}
string findLongestWord(string s, vector<string>& dictionary) {
    string best = "";
    for (auto& w : dictionary) {
        int i = 0;
        for (char ch : s) if (i < (int)w.size() && w[i] == ch) i++;
        if (i == (int)w.size()) {
            if ((int)w.size() > (int)best.size() ||
               ((int)w.size() == (int)best.size() && w < best))
                best = w;
        }
    }
    return best;
}
Time: O(|s| · Σ|wᵢ|) Space: O(1)