【每天一道算法题】近义词句子

本文介绍了一道算法题,涉及如何用近义词替换句子中的单词。给出的示例展示了如何处理近义词表和句子,通过并查集或直接建立映射来实现单词替换,并给出了Python代码实现。
摘要由CSDN通过智能技术生成

本文首发于我的公众号码农之屋(id: Spider1818),专注于干货分享,包含但不限于Java编程、网络技术、Linux内核及实操、容器技术等。欢迎大家关注,二维码文末可以扫。

 

题目描述

给你一个近义词表 synonyms 和一个句子 text , synonyms 表中是一些近义词对 ,你可以将句子 text 中每个单词用它的近义词来替换。

请你找出所有用近义词替换后的句子,按 字典序排序 后返回。

示例 1:

输入:

synonyms = [["happy","joy"],["sad","sorrow"],["joy","cheerful"]],

text = "I am happy today but was sad yesterday"

输出:

["I am cheerful today but was sad yesterday",

"I am cheerful today but was sorrow yesterday",

"I am happy today but was sad yesterday",

"I am happy today but was sorrow yesterday",

"I am joy today but was sad yesterday",

"I am joy today but was sorrow yesterday"] 

提示:

0 <= synonyms.length <= 10

synonyms[i].length == 2

synonyms[0] != synonyms[1]

所有单词仅包含英文字母,且长度最多为 10 。

text 最多包含 10 个单词,且单词间用单个空格分隔开。

 

解决思路

算法:

用并查集来将同义词归类,再把连通分量中的单词按字典序排序,最后整理成“根单词 => 同义词数组”的映射。在回溯时,检测下每一个单词是否有同义词,有就枚举、没有就直接用那个单词。

其实不用并查集,直接建立“根单词 => 同义词数组”的映射也是可以的。

Python代码实现

/** * 并查集 + 回溯 */var generateSentences = function (synonyms, text) {  const uf = new UnionFind()  for (const [a, b] of synonyms) {    uf.union(a, b)  }  const root2Blocks = uf.getBlocks()  for (const block of root2Blocks.values()) {    block.sort() // 每个连通分量内的单词按字典序排序  }
  const res = []  const tokens = text.split(' ')
  function backtrack (i, acc) {    if (i === tokens.length) {      res.push(acc)      return    }      const token = tokens[i]    const rootWord = uf.getRoot(token)    if (rootWord) { // 如果有同义词      for (const word of root2Blocks.get(rootWord)) {        backtrack(i + 1, acc + (i === 0 ? '' : ' ') + word)      }    } else {      backtrack(i + 1, acc + (i === 0 ? '' : ' ') + token)    }  }
  backtrack(0, '')  return res};
// 并查集class UnionFind {  constructor () {    this.father = new Map()  }
  getRoot (x) {    if (this.father.get(x) === x) return x    const res = this.getRoot(this.father.get(x))    this.father.set(x, res)    return res  }
  union (x, y) {    if (!this.father.has(x)) this.father.set(x, x)    if (!this.father.has(y)) this.father.set(y, y)
    const xx = this.getRoot(x)    const yy = this.getRoot(y)    if (xx !== yy) {      this.father.set(xx, yy)    }  }
  getBlocks () {    const res = new Map() // 根 => 连通分量    for (const curr of this.father.keys()) {      const father = this.getRoot(curr)      if (!res.has(father)) {        res.set(father, [])      }      res.get(father).push(curr)    }    return res  }}

 

我的公众号「码农之屋」(id: Spider1818) ,分享的内容包括但不限于 Linux、网络、云计算虚拟化、容器Docker、OpenStack、Kubernetes、SDN、OVS、DPDK、Go、Python、C/C++编程技术等内容,欢迎大家关注。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值