• 边工作边刷题: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"
    
    
  • 相关阅读:
    排版字号对应多少pt
    C# 定义常量 两种实现方法
    HttpApplication 类,HttpApplicationState 类
    [ASP.net教程]ASP.NET保存信息总结(Application、Session、Cookie、ViewState和Cache等)
    sqlserver 汉字转拼音(转载)
    几个不错的echarts +百度地图 案例
    ECharts 实现地图散点图上(转载)
    ECharts 散点图+百度地图(案例转载)
    SQL统计部门人数,人数为0的部门也要显示出来
    待看文档
  • 原文地址:https://www.cnblogs.com/absolute/p/5815784.html
Copyright © 2020-2023  润新知