1. 程式人生 > >LeetCode刷題EASY篇同構字串Isomorphic Strings

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;
    }
}