1. 程式人生 > 其它 >leetcode 205. 同構字串(hash)

leetcode 205. 同構字串(hash)

技術標籤:leetcode字串leetcodejava演算法

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

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

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

示例 1:

輸入: s = “egg”, t = “add”
輸出: true

程式碼

class Solution {
    public boolean isIsomorphic(String s, String t) {

        Map<Character,Character>
map=new HashMap<>(); Map<Character,Character> map2=new HashMap<>(); for(int i=0;i<s.length();i++) { if(map.containsKey(s.charAt(i))&&t.charAt(i)!=map.get(s.charAt(i))||map2.containsKey(t.charAt(i))&&s.charAt(i)!=map2.get(t.
charAt(i)))//出現一對多的情況,說明無法匹配 return false; map.put(s.charAt(i),t.charAt(i));//字串s和t的字母相互對映 map2.put(t.charAt(i),s.charAt(i)); } return true; } }