zoukankan      html  css  js  c++  java
  • 【leetcode】290. Word Pattern

    题目如下:

    解题思路:本题的关键是pattern和word之间必须是一对一的关系。因此需要建立pattern->word和word->pattern两种映射,这两种映射可用两个字典分别保存。

    代码如下:

    class Solution(object):
        def wordPattern(self, pattern, str):
            """
            :type pattern: str
            :type str: str
            :rtype: bool
            """
            words = str.split(' ')
            if len(pattern) != len(words):
                return False
            dic_p_to_w = {}
            dic_w_to_p = {}
            for p,w in zip(pattern,words):
                if p not in dic_p_to_w and w not in dic_w_to_p:
                    dic_p_to_w[p] = w
                    dic_w_to_p[w] = p
                elif p in dic_p_to_w and w in dic_w_to_p:
                    if (dic_p_to_w[p] == w and dic_w_to_p[w] == p) == False:
                        return False
                else:
                    return False
            return True
  • 相关阅读:
    网页抓取
    基本数据结构
    小节
    顺序统计量
    线性时间排序
    快速排序
    堆排序 Heapsort
    大数运算
    趣味题,文本中洞的数量
    nginx config配置
  • 原文地址:https://www.cnblogs.com/seyjs/p/9275607.html
Copyright © 2011-2022 走看看