zoukankan      html  css  js  c++  java
  • 【leetcode】1258. Synonymous Sentences

    题目如下:

    Given a list of pairs of equivalent words synonyms and a sentence text, Return all possible synonymous sentences sorted lexicographically.

    Example 1:

    Input:
    synonyms = [["happy","joy"],["sad","sorrow"],["joy","cheerful"]],
    text = "I am happy today but was sad yesterday"
    Output:
    ["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"]

    Constraints:

    • 0 <= synonyms.length <= 10
    • synonyms[i].length == 2
    • synonyms[0] != synonyms[1]
    • All words consist of at most 10 English letters only.
    • text is a single space separated sentence of at most 10 words.

    解题思路:我的方法是替换,依次遍历synoyms,如果text中存在synoyms[i][0],把text中的第一个synoyms[i][0]替换成synoyms[i][1];同样,如果存在synoyms[i][1],把text中的第一个synoyms[i][1]替换成synoyms[i][0]。然后再对替换过的text做同样的操作,直到不能替换位置。考虑到synoyms[i][0] = 'a',而text中存在'an'这种情况,为了防止误替换,可以把每个单词的前后都加上'#'作为分隔。

    代码如下:

    class Solution(object):
        def generateSentences(self, synonyms, text):
            """
            :type synonyms: List[List[str]]
            :type text: str
            :rtype: List[str]
            """
            text = '#' + text.replace(' ', '#') + '#'
            queue = [text]
            for (w1,w2) in synonyms:
                for text in queue :
                    newtext = text.replace('#' + w1+'#','#' + w2+'#',1)
                    if newtext != text and newtext not in queue:
                        queue.append(newtext)
                    newtext = text.replace('#' + w2 + '#', '#' + w1 + '#',1)
                    if newtext != text and newtext not in queue:
                        queue.append(newtext)
            res = []
            for i in sorted(queue):
                newtext = i.replace('#', ' ')
                res.append(newtext[1:-1])
            return res
  • 相关阅读:
    Codeforces Round #297 (Div. 2) 525C Ilya and Sticks(脑洞)
    全栈必备 JavaScript基础
    2014-04-19编程之美初赛题目及答案解析
    doT js模板入门 2
    一篇关于arc下内存管理的老文章,包含各种冷门修饰符(关于内存),写的较好,mark
    MyBatis官方教程及源代码解析——mapper映射文件
    Android中图片的三级缓存策略
    python字符串/元组/列表/字典互转
    关于字节对齐的理解
    阿里云服务器ecs配置之安装redis服务
  • 原文地址:https://www.cnblogs.com/seyjs/p/11878846.html
Copyright © 2011-2022 走看看