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

    题目链接:https://leetcode.com/problems/word-pattern/

    思路分析:题目要求判断在pattern中的字符与str中的非空word之间是否存在双射,解法如代码所示。

     

    循环不变量:当 I = k 时,并进行迭代时,pattern[0..i-1]与strings[0..i-1]之间满足双射关系

    循环不变量证明:

    1> 初始化:当 I = 0时,I – 1 = -1,则pattern[0..i-1]与strings[0..i-1]都为空,满足循环不变式

    2> 保持:分情况讨论:

    1. 当 hashtable[pattern[i]]不为None时,即pattern[i]存在于pattern[0..i-1]中,因为满足双射,则strings[i]应该和strings[hashtable[pattern[i]]]相等
    2. 当hashtable[pattern[i]]为None时,则pattern[i]不存在于pattern[0..i-1]中,因为同样要满足双射,则strings[i]必须不存在于strings[0..i-1]中,如果strings[i]存在于strings[0..i-1]中,则strings[i]同时映射在pattern[0..i]中的两个不同字符,不满足双射

    3>终止:当i==len(pattern)时,循环终止,此时pattern[0..len-1]与strings[0..len-1]之间存在双射

    算法证明成立

    代码如下:

    class Solution(object):
        def wordPattern(self, pattern, str):
            """
            :type pattern: str
            :type str: str
            :rtype: bool
            """
            strings = str.split()
            hashtable, charset = {}, set()
    
            if len(pattern) != len(strings): return False
            for i, ch in enumerate(pattern):
                string = hashtable.get(ch)
                if not string:
                    if strings[i] in hashtable.values():
                        return False
                    hashtable[ch] = strings[i]
                else:
                    if string != strings[i]:
                        return False
            return True
  • 相关阅读:
    自动换行的两种代码(C#)
    C#的SubString(int start,int end);
    php数组添加元素的方法
    php通过生成动态变量(变量名中还有变量)
    php定义空的数组
    php的$GLOBALS例子
    WINCRIS的使用
    java的PreparedStatement中使用like时的问题
    php发送get请求
    在HTML中使用object和embed标签插入视频
  • 原文地址:https://www.cnblogs.com/tallisHe/p/5313817.html
Copyright © 2011-2022 走看看