• 边工作边刷题:70天一遍leetcode: day 86


    Word Pattern II
    要点:

    • 注意与I的差异,其实题不难,看到这种迷乱的,首先要想到backtrack
    • 1:1 mapping两个条件:p in and str in, or p not in and str not in values().

    错误点:

    • false的退出条件是pattern没有足够字符1:1了(i.e., len(pattern)>len(str)),但true的条件是pattern和str都比完了

    https://repl.it/CekC/1

    # Given a pattern and a string str, find if str follows the same pattern.
    
    # Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty substring in str.
    
    # Examples:
    # pattern = "abab", str = "redblueredblue" should return true.
    # pattern = "aaaa", str = "asdasdasdasd" should return true.
    # pattern = "aabb", str = "xyzabcxzyabc" should return false.
    # Notes:
    # You may assume both pattern and str contains only lowercase letters.
    
    # Hide Company Tags Dropbox Uber
    # Hide Tags Backtracking
    # Hide Similar Problems (E) Word Pattern
    
    
    class Solution(object):
        def wordPatternMatch(self, pattern, str):
            """
            :type pattern: str
            :type str: str
            :rtype: bool
            """
            pattern_map = {}
            def helper(pattern, str):
                if not pattern and not str:
                    return True
                
                if not pattern or not str:
                    return False
                    
                if len(pattern)>len(str):
                    return False
                
                p = pattern[0]
                if p in pattern_map:
                    if str[:len(pattern_map[p])]!=pattern_map[p]:
                        return False
                    else:
                        return helper(pattern[1:], str[len(pattern_map[p]):])
                
                for i in xrange(len(str)):
                    substr = str[:i+1]
                    if substr not in pattern_map.values():
                        pattern_map[p]=str[:i+1]
                        if helper(pattern[1:], str[i+1:]):
                            return True
                        del pattern_map[p]
                
                return False
            
            return helper(pattern, str)
     
    sol = Solution()
    assert sol.wordPatternMatch("abab", "redblueredblue")==True, "must be True"
    assert sol.wordPatternMatch("aaaa", "asdasdasdasd")==True, "must be True"
    assert sol.wordPatternMatch("aabb", "xyzabcxzyabc")==False, "must be False"
    
    
  • 相关阅读:
    tomcat剖析(一)
    java内存区域
    经典排序算法-冒泡与选择
    使用docker安装mysql服务
    C语言博客作业--结构体
    C博客作业--指针
    C语言博客作业--字符数组
    C语言博客作业--数组
    C语言博客作业--数据类型
    C语言博客作业--函数
  • 原文地址:https://www.cnblogs.com/absolute/p/5815784.html
Copyright © 2020-2023  润新知