205Isomorphic Strings

来源:互联网 发布:那些年听过的网络歌曲 编辑:程序博客网 时间:2024/06/08 15:19

题目链接:https://leetcode.com/problems/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.

解题思路:
这题的考点是 HashMap 的用法。
有点像凯撒密码,一个字母和一个字母一一对应。一个字母可以与其本身对应。
因此判断两个字符串是否是同构,需要从两方面比较。对于两个字符串相同位置的两个字符来说:
1. 若第一个字符包含在 HashMap 的键集中,则第一个字符对应的值若不等于第二个字符,键 -> 值的映射不成立,返回 false
2. 若第二个字符包含在 HashMap 的值集中,则第二个字符对应的键若不等于第一个字符,值 -> 键的映射不成立,返回false
3. 此时说明键值对<第一个字符,第二个字符>不在 HashMap 中,则将它们添加进去

注意:有一种情况是,不同键对应相同值。例如:“ab””aa”

另一种方法是:
根据已知的映射关系,将第一个字符串翻译成一个新的字符串。最后将新字符串和第二个字符串相比。
已知关系是指:通过扫描第一个字符串和第二字符串对应字符来创建键值对。在此过程中,必须保证若键不存在,值也不存在。若值存在

代码实现:

0 0
原创粉丝点击