LeetCode 290. English law (python)

Topic Link

Description Title:
given a law and a pattern string str, str determines whether to follow the same rule.

Here follow the exact match means, for example, there is a corresponding pattern regularity in two-way connection between each letter string str and each non-empty word.

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
Description:
You assume pattern can contain only lowercase letters, str contains lowercase letters separated by a single space.

Problem-solving ideas:
the str on spaces divided into sstr, if the length of the pattern length and different sstr directly returns False
the pattern as the key, as a value into sstr dictionary, if the current through the key appears in the dictionary, it is determined dictionary the key's value is equal to a value corresponding to, not equal to False is returned
if the current key not appeared in the dictionary, determining the corresponding value has not occurred in the dictionary, there have been False is returned
if there have been no, add to the dictionary

class Solution(object):
    def wordPattern(self, pattern, str):
        """
        :type pattern: str
        :type str: str
        :rtype: bool
        """
        sstr=str.split(' ')
        if len(sstr)!=len(pattern):
            return False
        dic={}
        for i in range(len(pattern)):
            if pattern[i] in dic:
                if dic[pattern[i]]!=sstr[i]:
                    return False
            elif sstr[i] in dic.values():
                return False     
            else:
                dic[pattern[i]]=sstr[i]
        return True

Here Insert Picture Description

Comments area Answer:

        words = str.split(' ')
        if len(words) != len(pattern):
            return False
        return map(pattern.find, pattern) == map(words.index, words)

Guess you like

Origin blog.csdn.net/weixin_44740082/article/details/91994293