LeetCode刷题EASY篇同构字符串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.

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

什么是同构字符串?

两个个字符串的每个字母都匹配同一个映射关系,比如egg -> add的映射关系就是:e->a, g->d; foo与bar显然不满足,因为o->a同事o->r;paper和title满足,p->t, a->i, e->l, r->e

十分钟尝试

相同的字符的映射关系相同,这个就是判断的标准。很显然,可以用map保存映射关系,如果char相同,判断在map中是否存在,如果不存在,加入map,如果存在,判断映射关系是否相同。

class Solution {
    public boolean isIsomorphic(String s, String t) {
        Map<Character,Character> map=new  HashMap();
        for(int i=0;i<s.length();i++){
            Character tmpS=s.charAt(i);
            Character tmpT=t.charAt(i);
            if(map.containsKey(tmpS)){
                return map.get(tmpS)==tmpT;
            }
            else{
                map.put(tmpS,tmpT);
            }   
        }
          return true;
    }
}

代码貌似可以,但是有个情况没有cover。如果输入是[a,b]和[a,a],映射关系只是考虑了s到t,没有考虑t到s,从t看,a映射到a,a映射也到了b。在else分支中,如果没有包含当前key,但是当前T如果在map中已经以value形式存在,意味着不同的映射。

比如 a b 和a a的情况,第一个次a a存入map。map中为[a,a],第二次,key为b,在map中不存在,但是b对应的value也就是a已经存在,显然就是不同的映射。所以修改一下:

class Solution {
    public boolean isIsomorphic(String s, String t) {
        Map<Character,Character> map=new  HashMap();
        for(int i=0;i<s.length();i++){
            Character tmpS=s.charAt(i);
            Character tmpT=t.charAt(i);
            if(map.containsKey(tmpS)){
                if(map.get(tmpS)!=tmpT) 
                    return false;
            }
            else if(!map.containsValue(tmpT)){
                map.put(tmpS,tmpT);
            }   
            else{
                return false;
            }
        }
          return true;
    }
}

猜你喜欢

转载自blog.csdn.net/hanruikai/article/details/84984589