【leetcode】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.code

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.get

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

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

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

Note:
You may assume both s and t have the same length.io

解題思路:

首先,相同的地方必須相同這個條件能夠得出一個O(n^2)的算法class

class Solution:
    # @param {string} s
    # @param {string} t
    # @return {boolean}
    def isIsomorphic(self, s, t):
        ls = len(s)
        lt = len(t)
        if ls != lt:
            return False
        for i in range(ls):
            for j in range(ls):
                if s[i] == s[j]:
                    if t[i] != t[j]:
                        return False
        return True

可是很不幸超時了,因而咱們用hash的方法獲得另外一個更快的算法:map

class Solution:
    # @param {string} s
    # @param {string} t
    # @return {boolean}
    def isIsomorphic(self, s, t):
        ls = len(s)
        lt = len(t)
        if ls != lt:
            return False
        dic = {}
        dic2 = {}
        for i in range(ls):
            if s[i] not in dic.keys():
                dic[s[i]] = t[i]
            else:
                if dic[s[i]] != t[i]:
                    return False
            if t[i] not in dic2.keys():
                dic2[t[i]] = s[i]
            else:
                if dic2[t[i]] != s[i]:
                    return False
        return True
相關文章
相關標籤/搜索