返回介绍

solution / 0700-0799 / 0720.Longest Word in Dictionary / README_EN

发布于 2024-06-17 01:03:35 字数 5425 浏览 0 评论 0 收藏 0

720. Longest Word in Dictionary

中文文档

Description

Given an array of strings words representing an English Dictionary, return _the longest word in_ words _that can be built one character at a time by other words in_ words.

If there is more than one possible answer, return the longest word with the smallest lexicographical order. If there is no answer, return the empty string.

Note that the word should be built from left to right with each additional character being added to the end of a previous word. 

 

Example 1:

Input: words = ["w","wo","wor","worl","world"]
Output: "world"
Explanation: The word "world" can be built one character at a time by "w", "wo", "wor", and "worl".

Example 2:

Input: words = ["a","banana","app","appl","ap","apply","apple"]
Output: "apple"
Explanation: Both "apply" and "apple" can be built from other words in the dictionary. However, "apple" is lexicographically smaller than "apply".

 

Constraints:

  • 1 <= words.length <= 1000
  • 1 <= words[i].length <= 30
  • words[i] consists of lowercase English letters.

Solutions

Solution 1

class Solution:
  def longestWord(self, words: List[str]) -> str:
    cnt, ans = 0, ''
    s = set(words)
    for w in s:
      n = len(w)
      if all(w[:i] in s for i in range(1, n)):
        if cnt < n:
          cnt, ans = n, w
        elif cnt == n and w < ans:
          ans = w
    return ans
class Solution {
  private Set<String> s;

  public String longestWord(String[] words) {
    s = new HashSet<>(Arrays.asList(words));
    int cnt = 0;
    String ans = "";
    for (String w : s) {
      int n = w.length();
      if (check(w)) {
        if (cnt < n) {
          cnt = n;
          ans = w;
        } else if (cnt == n && w.compareTo(ans) < 0) {
          ans = w;
        }
      }
    }
    return ans;
  }

  private boolean check(String word) {
    for (int i = 1, n = word.length(); i < n; ++i) {
      if (!s.contains(word.substring(0, i))) {
        return false;
      }
    }
    return true;
  }
}
class Solution {
public:
  string longestWord(vector<string>& words) {
    unordered_set<string> s(words.begin(), words.end());
    int cnt = 0;
    string ans = "";
    for (auto w : s) {
      int n = w.size();
      if (check(w, s)) {
        if (cnt < n) {
          cnt = n;
          ans = w;
        } else if (cnt == n && w < ans)
          ans = w;
      }
    }
    return ans;
  }

  bool check(string& word, unordered_set<string>& s) {
    for (int i = 1, n = word.size(); i < n; ++i)
      if (!s.count(word.substr(0, i)))
        return false;
    return true;
  }
};
func longestWord(words []string) string {
  s := make(map[string]bool)
  for _, w := range words {
    s[w] = true
  }
  cnt := 0
  ans := ""
  check := func(word string) bool {
    for i, n := 1, len(word); i < n; i++ {
      if !s[word[:i]] {
        return false
      }
    }
    return true
  }
  for w, _ := range s {
    n := len(w)
    if check(w) {
      if cnt < n {
        cnt, ans = n, w
      } else if cnt == n && w < ans {
        ans = w
      }
    }
  }
  return ans
}
function longestWord(words: string[]): string {
  words.sort((a, b) => {
    const n = a.length;
    const m = b.length;
    if (n === m) {
      return a < b ? -1 : 1;
    }
    return m - n;
  });
  for (const word of words) {
    let isPass = true;
    for (let i = 1; i <= word.length; i++) {
      if (!words.includes(word.slice(0, i))) {
        isPass = false;
        break;
      }
    }
    if (isPass) {
      return word;
    }
  }
  return '';
}
impl Solution {
  pub fn longest_word(mut words: Vec<String>) -> String {
    words.sort_unstable_by(|a, b| (b.len(), a).cmp(&(a.len(), b)));
    for word in words.iter() {
      let mut is_pass = true;
      for i in 1..=word.len() {
        if !words.contains(&word[..i].to_string()) {
          is_pass = false;
          break;
        }
      }
      if is_pass {
        return word.clone();
      }
    }
    String::new()
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文