leetcode-205 <Isomorphic Strings>

题目描述:
Given two strings s and t, determine if they are isomorphic.

Two strings s and t 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

题目解析:
证明两个字符串是同构关系:在保持字符顺序的同时,必须用另一个字符替换所有出现的字符。 没有两个字符可以映射到同一个字符。

var isIsomorphic = function(s, t) {
    let sSet = new Set(s)
    let tSet = new Set(t)
    // 如果两个字符串出现的非重复字符的个数一致,表明满足同构的必要条件
    // 个数不一致 则说明有多个字符的映射关系
    if(sSet.size !== tSet.size){
        return false
    }
    // 用Map表来存储遍历的字符
    let map = new Map()
    for(let i =0;i<s.length;i++){
        // 如果存在于Map里 但是拿到的value对不上的话 则说明出现多个字符映射的关系
        if(map.has(s[i]) && map.get(s[i]) !== t[i]){
            return false
        }else{
            map.set(s[i], t[i])
        }
    }
    return true
};
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容