leetcode_290. Word Pattern 单词模式识别,识别句子中的单词模式,单词与模式的一一映射

题目:

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 word in str.

Examples:

  1. pattern = "abba", str = "dog cat cat dog" should return true.
  2. pattern = "abba", str = "dog cat cat fish" should return false.
  3. pattern = "aaaa", str = "dog cat cat dog" should return false.
  4. pattern = "abba", str = "dog dog dog dog" should return false.

Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.


题意:

给定一个模式串pattern和字符串str,判断str中的单词模式是不是pattern中的模式,例如"dog cat cat dog" 的单词构成是abba型的


代码:

class Solution(object):
    def wordPattern(self, pattern, str):
        """
        :type pattern: str
        :type str: str
        :rtype: bool
        """

        #wordlist = str.split(' ')    #可用python自带的split函数将str中的单词分离出来
        
        wordlist = []                   #不用split函数行进单词切分
        i = 0
        while i < len(str) :
            j=i
            temp = ''
            while j < len(str) and str[j] != ' ' :               #此处严重注意,若先判断str[j] != ' ',再判断j < len(str) ,则会报超出数组下标错误,故j < len(str) 条件一定要放在前面
                temp += str[j]
                j += 1
            
            wordlist.append(temp)           #将得到的单词存在list中
            i = j+1
        
        print wordlist
        
        if len(pattern) != len(wordlist) :
            return False
        else :
            pattern_map = dict()          #用两个字典,判断一一映射,与leetcode_205 题一样
            for i in range(len(pattern)) :
                if pattern[i] not in pattern_map :
                    pattern_map[pattern[i]] = wordlist[i]
                else :
                    if pattern_map[pattern[i]] != wordlist[i] :
                        return False
            
            word_map = dict()
            for i in range(len(wordlist)) :
                if wordlist[i] not in word_map :
                    word_map[wordlist[i]] = pattern[i]
                else :
                    if word_map[wordlist[i]] != pattern[i] :
                        return False                
            
            return True
            
  

笔记:

1、循环判断的时候,关于数组下标的条件一定要放在前面,不然老是报数组下标越界错误

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值