当前位置: 首页 > news >正文

[NeetCode 150] Foreign Dictionary

Foreign Dictionary

There is a foreign language which uses the latin alphabet, but the order among letters is not “a”, “b”, “c” … “z” as in English.

You receive a list of non-empty strings words from the dictionary, where the words are sorted lexicographically based on the rules of this new language.

Derive the order of letters in this language. If the order is invalid, return an empty string. If there are multiple valid order of letters, return any of them.

A string a is lexicographically smaller than a string b if either of the following is true:

The first letter where they differ is smaller in a than in b.
There is no index i such that a[i] != b[i] and a.length < b.length.

Example 1:

Input: ["z","o"]Output: "zo"

Explanation:
From “z” and “o”, we know ‘z’ < ‘o’, so return “zo”.

Example 2:

Input: ["hrn","hrf","er","enn","rfnn"]Output: "hernf"

Explanation:

from “hrn” and “hrf”, we know ‘n’ < ‘f’
from “hrf” and “er”, we know ‘h’ < ‘e’
from “er” and “enn”, we know get ‘r’ < ‘n’
from “enn” and “rfnn” we know ‘e’<‘r’
so one possibile solution is “hernf”

Constraints:

The input words will contain characters only from lowercase ‘a’ to ‘z’.

1 <= words.length <= 100
1 <= words[i].length <= 100

Solution

From the order of the words, we can get the priority between 2 characters, which can be represented as a directed edge between them. When we organize all of the edges, we can get a DAG (Directed Acyclic Graph). Then we just need to do a topological sort with this DAG and get the answer.

Code

import queueclass Solution:def foreignDictionary(self, words: List[str]) -> str:edges = {c: set() for word in words for c in word}in_deg = {c: 0 for word in words for c in word}for i in range(len(words) - 1):w1, w2 = words[i], words[i + 1]minLen = min(len(w1), len(w2))if len(w1) > len(w2) and w1[:minLen] == w2[:minLen]:return ''for j in range(minLen):if w1[j] != w2[j]:edges[w1[j]].add(w2[j])breakfor value in edges.values():for c in value:in_deg[c] += 1print(edges)print(in_deg)que = queue.Queue()for key, value in in_deg.items():if value == 0:que.put(key)ans = []while not que.empty():cur = que.get()ans.append(cur)for nxt in edges.get(cur, []):in_deg[nxt] -= 1if in_deg[nxt] == 0:que.put(nxt)print(ans)if len(ans) != len(in_deg):return ''return ''.join(ans)
http://www.lryc.cn/news/470573.html

相关文章:

  • 小新学习K8s第一天之K8s基础概念
  • 如何用终端批量修改一个文件夹里面所有图片的后缀名?
  • 关于AI网络架构的文章
  • 【ChatGPT】在多轮对话中引导 ChatGPT 保持一致性
  • 【Chapter 7】因果推断中的机器学习:从T-学习器到双重稳健估计
  • vim的使用方法
  • OPPO携手比亚迪共同探索手机与汽车互融新时代
  • Apache Linkis:重新定义计算中间件
  • go gorm简单使用方法
  • 【c++高级篇】--多任务编程/多线程(Thread)
  • 【力扣专题栏】两数相加,如何实现存储在链表中的整数相加?
  • SOLID - 接口隔离原则(Interface Segregation Principle)
  • arrylist怎么让他变得不可修改
  • SpringMVC实战(3):拓展
  • Vue应用中使用xlsx库实现Excel文件导出的完整指南
  • 【数据分析】Power BI的使用教程
  • 融合ASPICE与敏捷开发:探索汽车软件开发的最佳实践
  • 后台管理系统的通用权限解决方案(三)SpringBoot整合Knife4j生成接口文档
  • 保研考研机试攻略:python笔记(1)
  • 在浏览器中运行 Puppeteer:解锁新能力
  • Kafka消费者故障,出现活锁问题如何解决?
  • pytorch 交叉熵损失函数 BCELoss
  • 【进阶】面向对象之接口(多学三招)
  • linux上trace code的几种方法
  • 文件操作(1) —— 文件基础知识
  • 4K双模显示器7款评测报告
  • 2024.10.24华为(留学生)笔试题解
  • 基于neo4j的医疗问诊系统
  • java :String 类
  • 关于非中文或者url文本不换行的问题