码迷,mamicode.com
首页 > 其他好文 > 详细

828. 字模式

时间:2020-03-25 00:55:00      阅读:79      评论:0      收藏:0      [点我收藏+]

标签:inpu   ima   count   testcase   测试数据   elf   大致   数值   pdo   

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

 

 

828. 字模式

标签:inpu   ima   count   testcase   测试数据   elf   大致   数值   pdo   

原文地址:https://www.cnblogs.com/yunxintryyoubest/p/12563482.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!