Lintcode 828. Word Pattern (Easy) (Python)

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

Given pattern = “abba”, str = “dog cat cat dog”, return true.
Given pattern = “abba”, str = “dog cat cat fish”, return false.
Given pattern = “aaaa”, str = “dog cat cat dog”, return false.
Given pattern = “abba”, str = “dog dog dog dog”, return false.

Code:

1.

class Solution:
    """
    @param pattern: a string, denote pattern string
    @param str: a string, denote matching string
    @return: an boolean, denote whether the pattern string and the matching string match or not
    """
    def wordPattern(self, pattern, str):
        # write your code here
        st = str.split(' ')
        map1, map2 = {}, {}
        if len(st)!=len(pattern):
            return False
        for i in range(len(st)):
            if st[i] in map2 and pattern[i] not in map1:
                return False
            elif pattern[i] in map1 and map1[pattern[i]] != st[i]:
                return False
            map1[pattern[i]] = st[i]
            map2[st[i]] = 1
        return True

2.

class Solution:
    """
    @param pattern: a string, denote pattern string
    @param str: a string, denote matching string
    @return: an boolean, denote whether the pattern string and the matching string match or not
    """
    def wordPattern(self, pattern, str):
        # write your code here
        st = str.split(' ')
        if len(st)!=len(pattern):
            return False
        return len(set(pattern)) == len(set(st)) == len(set(zip(st, pattern)))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值