Leetcode

2019-02-09

2019-02-09  本文已影响0人  ruicore
LeetCode 290. Word Pattern.jpg

LeetCode 290. Word Pattern

Description

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.

Example 1:

Input: pattern = "abba", str = "dog cat cat dog"
Output: true

Example 2:

Input:pattern = "abba", str = "dog cat cat fish"
Output: false

Example 3:

Input: pattern = "aaaa", str = "dog cat cat dog"
Output: false

Example 4:

Input: pattern = "abba", str = "dog dog dog dog"
Output: false

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

描述

给定一种 pattern(模式) 和一个字符串 str ,判断 str 是否遵循相同的模式。

这里的遵循指完全匹配,例如, pattern 里的每个字母和字符串 str 中的每个非空单词之间存在着双向连接的对应模式。

示例1:

输入: pattern = "abba", str = "dog cat cat dog"
输出: true

示例 2:

输入:pattern = "abba", str = "dog cat cat fish"
输出: false

示例 3:

输入: pattern = "aaaa", str = "dog cat cat dog"
输出: false

示例 4:

输入: pattern = "abba", str = "dog dog dog dog"
输出: false

说明:
你可以假设 pattern 只包含小写字母, str 包含了由单个空格分隔的小写字母。

思路

# -*- coding: utf-8 -*-
# @Author:             何睿
# @Create Date:        2019-02-08 11:19:39
# @Last Modified by:   何睿
# @Last Modified time: 2019-02-09 09:43:27


class Solution:
    def wordPattern(self, pattern: 'str', str: 'str') -> 'bool':
        #  字典,记录对应关系
        match = {}
        # 将给定的单词用空格区分
        word = str.split(" ")
        # 如果长度不相等,直接返回False
        if len(pattern) != len(word): return False
        for i in range(len(pattern)):
            # 如果模式串pattern[i]不在字典中(键)
            if pattern[i] not in match:
                # 如果此时的单词在字典的值中,说明已经有模式串的字符与当前单词匹配,返回False
                if word[i] in match.values():
                    return False
                # 如果单词没有出现在字典的值中,添加当前模式串与单词的对应关系
                match[pattern[i]] = word[i]
            else:
                # 如果当前模式串的键已经在字典中,检查字典的值和当前单词是否相等,不等返回False
                if match[pattern[i]] != word[i]:
                    return False
        return True

源代码文件在这里.
©本文首发于何睿的博客,欢迎转载,转载需保留文章来源,作者信息和本声明.

上一篇 下一篇

猜你喜欢

热点阅读