word pattern problems

# Word Pattern
class Solution(object):
    def wordPattern(self, pattern, str):
        """
        :type pattern: str
        :type str: str
        :rtype: bool
        """
        strs = str.split()
        if len(pattern) != len(strs):
            return False
        dict1 = {}
        dict2 = {}
        for i in range(len(pattern)):
            if pattern[i] not in dict1 and strs[i] not in dict2:
                dict1[pattern[i]] = strs[i]
                dict2[strs[i]] = pattern[i]
            elif pattern[i] in dict1 and strs[i] in dict2:
                if dict1[pattern[i]] != strs[i] or dict2[strs[i]] != pattern[i]:
                    return False
            else:
                return False
        return True
# Isomorphic Strings
class Solution(object):
    def isIsomorphic(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        # map the two s, make sure it has one to one mapping realationship
        if len(s) != len(t):
            return False
        charMap1 = {}
        charMap2 = {}
        for i in range(len(s)):
            if s[i] not in charMap1 and t[i] not in charMap2:
                charMap1[s[i]] = t[i]
                charMap2[t[i]] = s[i]
            elif s[i] in charMap1 and t[i] in charMap2:
                if charMap1[s[i]] != t[i] or charMap2[t[i]] != s[i]:
                    return False
            else:
                return False
        return True

e290. Word Pattern
e205. Isomorphic Strings

你可能感兴趣的:(word pattern problems)