zoukankan      html  css  js  c++  java
  • 828. 字模式

    828. 字模式

    中文English

    给定一个模式串pattern和一个字符串str,请问strpattern是否遵循相同的模式。
    这里遵循模式指的是一个完全匹配,即在pattern中的每个不同的字母和str中每个非空的单词之间有一个双向映射的模式对应。

    样例

    样例1

    输入: pattern = "abba" and str = "dog cat cat dog"
    输出: true
    解释:
    str的模式是 abba
    

    样例2

    输入: pattern = "abba" and str = "dog cat cat fish"
    输出: false
    解释:
    str的模式是 abbc
    

    样例3

    输入: pattern = "aaaa" and str = "dog cat cat dog"
    输出: false
    解释:
    str的模式是 abba
    

    样例4

    输入: pattern = "abba" and str = "dog cat cat fish"
    输出: false
    解释:
    str的模式是 abbc
    

    注意事项

    您可以认为模式串pattern只包含小写字母,而str包含由单个空间分隔的小写单词组成。

    输入测试数据 (每行一个参数)如何理解测试数据?
    class Solution:
        """
        @param pattern: a string, denote pattern string
        @param teststr: a string, denote matching string
        @return: an boolean, denote whether the pattern string and the matching string match or not
        """
        '''
        大致思路:
        1.首先根据空格进行切割teststr,单个字符进行分割
        2.如果pattern和首字母字符串长度不相等,直接返回False
        3.循环进行校对,根据pattern和首字母字符串进行字典映射,如果存在不符合的,则返回False,否则True
        '''
        def wordPattern(self,pattern, teststr):
            dic = {}
            return_dic = teststr.split(' ')
            ##首先判断长度是否相等
            if len(return_dic) != len(pattern):
                return False
            
            #否则
            count = -1
            for i in pattern:
                count += 1
                if i not in dic and return_dic[count] not in dic.values():
                    #加进来,不做校验
                    dic['%s'%i] = return_dic[count]
    
                #否则,说明是重复的数值,需要进行校验
                if i in dic:
                    #否则,说明是重复的数值,需要进行校验
                    if dic['%s'%i] != return_dic[count]:
                        return False    
                else:
                    return False 
            return True

  • 相关阅读:
    《火影忍者:究级风暴》渲染技术究极解析!
    动态数组和内置数组转换范例
    固定视角
    旋转
    时间间隔操作
    编辑器的一些批处理脚本
    访问GUItexture
    血槽制作
    动画循环播放
    软件测试修炼之道之——重现问题(上)
  • 原文地址:https://www.cnblogs.com/yunxintryyoubest/p/12563482.html
Copyright © 2011-2022 走看看