(LeetCode)Isomorphic Strings — 同構字串

NO IMAGE

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.

Subscribe to see which companies asked this question

解題分析:

這裡的意思和前幾天刷的一道題目很像。就是判斷字串的結構,這裡可以說判斷構成,

舉例:

egg 與 add, 這裡儲存 e 對應著 a,  g 對應著 d.然後再判斷的時候發現有問題,對應不上,說明就不是同構的。

# -*- coding:utf-8 -*-
__author__ = 'jiuzhang'
class Solution(object):
def isIsomorphic(self, s, t):
s_list = list(s)
t_list = list(t)
if len(s) != len(t):
return False
sDict, tDict = {}, {}
for i, j in zip(s_list, t_list):
if i not in sDict:
sDict[i] = j
if j not in tDict:
tDict[j] = i
if tDict[j] != i or sDict[i] != j:
return False
return True