LeetCode 205. Isomorphic Strings
Description
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.
Example 1:
Input: s = "egg", t = "add"
Output: true
Example 2:
Input: s = "foo", t = "bar"
Output: false
Example 3:
Input: s = "paper", t = "title"
Output: true
描述
給定兩個(gè)字符串 s 和 t,判斷它們是否是同構(gòu)的妙蔗。
如果 s 中的字符可以被替換得到 t 杀狡,那么這兩個(gè)字符串是同構(gòu)的咸灿。
所有出現(xiàn)的字符都必須用另一個(gè)字符替換,同時(shí)保留字符的順序赖舟。兩個(gè)字符不能映射到同一個(gè)字符上攻走,但字符可以映射自己本身。
示例 1:
輸入: s = "egg", t = "add"
輸出: true
示例 2:
輸入: s = "foo", t = "bar"
輸出: false
示例 3:
輸入: s = "paper", t = "title"
輸出: true
思路
- 這道題我們使用一個(gè)字典况鸣,鍵為s中的字符,值為t中的字符竹观,我們要求鍵和值要一一對(duì)應(yīng).
# -*- coding: utf-8 -*-
# @Author: 何睿
# @Create Date: 2019-01-21 11:56:34
# @Last Modified by: 何睿
# @Last Modified time: 2019-01-21 19:36:15
class Solution:
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
# 字典镐捧,鍵為s中的字符,值為t中的字符
# 鍵和值必須一一對(duì)應(yīng)
res = {}
for x, y in zip(s, t):
# 若鍵存在臭增,則其值一定要和y相等
if x in res:
if not res.get(x) == y: return False
else:
# 若y已經(jīng)作為其他鍵的值懂酱,直接返回False,因?yàn)檫@里要求鍵值一一對(duì)應(yīng)
if y in res.values(): return False
else: res[x] = y
# 上面的條件都滿足速址,返回True
return True
源代碼文件在這里.
?本文首發(fā)于何睿的博客玩焰,歡迎轉(zhuǎn)載由驹,轉(zhuǎn)載需保留文章來源芍锚,作者信息和本聲明.