1. 程式人生 > 其它 >205. 同構字串(陣列、map)2

205. 同構字串(陣列、map)2

技術標籤:LeetCode

給定兩個字串s和t,判斷它們是否是同構的。

如果s中的字元可以被替換得到t,那麼這兩個字串是同構的。

所有出現的字元都必須用另一個字元替換,同時保留字元的順序。兩個字元不能對映到同一個字元上,但字元可以對映自己本身。

示例 1:

輸入: s = "egg", t = "add"
輸出: true
示例 2:

輸入: s = "foo", t = "bar"
輸出: false
示例 3:

輸入: s = "paper", t = "title"

輸出: true
說明:
你可以假設s和 t 具有相同的長度。

解法一:陣列(不推薦,雖然速度快,但是不能解決漢字)

public class Solution {
    public boolean isIsomorphic(String s1, String s2) {
        int[] m = new int[512];
        for (int i = 0; i < s1.length(); i++) {
            if (m[s1.charAt(i)] != m[s2.charAt(i)+256]) return false;
            m[s1.charAt(i)] = m[s2.charAt(i)+256] = i+1;
        }
        return true;
    }
}

解法二:map(推薦,雖然速度慢,但是能解決漢字這種情況)

public class Solution {
    public boolean isIsomorphic(String s, String t) {
        if(s == null || s.length() <= 1) return true;
        HashMap<Character, Character> map = new HashMap<Character, Character>();
        for(int i = 0 ; i< s.length(); i++){
            char a = s.charAt(i);
            char b = t.charAt(i);
            if(map.containsKey(a)){
                if(map.get(a).equals(b))
                continue;
                else
                return false;
            }else{
                if(!map.containsValue(b))
                map.put(a,b);
                else return false;
            }
        }
        return true;
    }
}