1. 程式人生 > >[leetcode: Python]205. Isomorphic Strings

[leetcode: Python]205. Isomorphic Strings

題目:
Given two strings s and t, determine if they are isomorphic.

Two strings are isomorphic if the characters in s can be replaced to get t.

All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.

For example,
Given "egg", "add", return true.

Given "foo", "bar", return false.

Given "paper", "title", return true.

Note:
You may assume both s and t have the same length.
假定s和t的長度一樣。

方法一:效能49ms

class Solution(object):
    def isIsomorphic(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
hashmap = {} mapval = {} for i in xrange(len(s)): if s[i] in hashmap: if hashmap[s[i]] != t[i]: return False elif t[i] in mapval: return False else: hashmap[s[i]] = t[i] mapval[t[i]] = True
return True

這個演算法是我已知的效能最好的了。。