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.
public boolean isIsomorphic(String s, String t) { if(s.length() != t.length()) return false; Map<Character, Character> mapS = new HashMap<>(), mapT = new HashMap<>(); for(int i=0; i<s.length(); i++) { char cs = s.charAt(i); char ct = t.charAt(i); if(!mapS.containsKey(cs)) { mapS.put(cs, ct); } else if(mapS.get(cs) != ct) { return false; } if(!mapT.containsKey(ct)) { mapT.put(ct, cs); } else if(mapT.get(ct) != cs) { return false; } } return true; }
C++的代码:
bool isIsomorphic(string s, string t) { if(s.size() != t.size()) return false; unordered_map<char, char> ms, mt; for(size_t i=0; i<s.size(); i++) { if(ms.count(s[i])) { if(ms[s[i]] != t[i]) return false; } else { ms[s[i]] = t[i]; } if(mt.count(t[i])) { if(mt[t[i]] != s[i]) return false; } else { mt[t[i]] = s[i]; } } return true; }
相关推荐
python python_leetcode题解之205_Isomorphic_Strings.py
标题 "LeetCode209 - Isomorphic Strings" 涉及到的是一个计算机科学与编程相关的算法问题,主要探讨字符串的映射关系。在描述中,“映射字符串”这一概念指出我们要研究的是如何通过一种映射规则来比较两个字符串...
205.Isomorphic Strings-| | | 217.包含重复的-| | | 219.包含重复的II-| | | 242.有效字谜-| | | 268.缺少编号-| | | 344.反向字符串-| | | 345.一个字符串的反向元音-| | | 349.两个数组的交集-| | | 374.猜测数字...
# [LeetCode](https://leetcode.com/problemset/algorithms/)  [![License]...
LeetCode 205的题目是“同构字符串”(Isomorphic Strings),要求判断两个字符串是否是同构的。如果字符串s可以通过字符替换得到字符串t,那么这两个字符串是同构的。所有出现的字符都必须用另一个字符替换,同时...
本题解将深入探讨Python解冑LeetCode第205题——"同构字符串"(Isomorphic Strings)。 同构字符串是指两个字符串s和t,它们之间存在一个一对一的映射关系,即每个字符在s中都有一个特定的字符对应t中的另一个字符...
从标题和描述中可以看到,本文主要关注于LeetCode原题的总结,涵盖了162个题目,包括Find Peak Element、Isomorphic Strings、Group Shifted Strings等,这些题目都是Google Onsite面经中的常见题目。 下面将对这些...
4 Isomorphic Strings 25 5 Word Ladder 27 6 Word Ladder II 29 7 Median of Two Sorted Arrays 33 8 Kth Largest Element in an Array 35 9 Wildcard Matching 37 10 Regular Expression Matching in Java 39 11 ...
IsomorphicStrings_lc205 lowestCommonAncestor_lc235 Netease 2018 - 2019 年度网易Android、Java岗算法题目汇总 最大兴趣值(MaxInterest) 数塔问题(BalancedTower) 丰收(Harvest) 牛牛找工作(FindJob) 数对