同構字符串

原題

  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.
  For example,
  Given "egg", "add", return true.
  Given "foo", "bar", return false.
  Given "paper", "title", return true.java

題目大意

  給定兩個字符串s和t,判斷它們是不是同構的。若是字符串s能夠經過字符替換的方式獲得字符串t,則稱s和t是同構的。字符的每一次出現都必須被其對應字符所替換,同時還須要保證原始順序不發生改變。兩個字符不能映射到同一個字符,可是字符能夠映射到其自己。算法

解題思路

  【只要s和t知足一一映射就能夠了】
  使用一個哈希表map維護兩個字符串中字符的映射關係,同時用一個set保存映射的值。(s[i], t[i]),如是s[i]鍵沒有在map中出現過而且t[i]沒有在set中出現過,就加入到映射關係中,t[i]值已經出現過,說明是多對一映射,不符合返回false。s[i]鍵若是已經出現過,設爲s[k],對應的映射值爲t[k]),即s[i]==s[k],則找出s[k]的對對應值t[k],若是t[i]!=t[k],說明一個同一個字符存在兩個不一樣的映射,兩個字符串不是同構的,返回false,繼續處理下一個字符,直到結束。spa

代碼實現

算法實現類.net

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class Solution {

    public boolean isIsomorphic(String s, String t) {

        // 兩個字符串都爲空
        if (s == null && t == null) {
            return true;
        }
        // 只有一個爲空
        else if (s == null || t == null) {
            return false;
        }
        // 兩個字符串的長度都爲0
        else if (s.length() == 0 && t.length() == 0) {
            return true;
        }
        // 兩個字符串的長度不相等
        else if (s.length() != t.length()) {
            return false;
        }

        // 保存映射關係 
        Map<Character, Character> map = new HashMap<>(s.length());
        Set<Character> set = new HashSet<>(t.length());
        char sChar;
        char tChar;
        for (int i = 0; i < s.length(); i++) {
            sChar = s.charAt(i);
            tChar = t.charAt(i);

            // 鍵未出現過,就保存映射關係
            if (!map.containsKey(sChar)) {
                if (set.contains(tChar)) {
                    return false;
                } else {
                    map.put(s.charAt(i), t.charAt(i));
                    set.add(tChar);
                }
            }
            // 如是鍵已經出現過
            else {

                // 原先的鍵映射的值是map.get(sChar),如今要映射的值是tChar
                // 若是兩個值不相等,說明已經映射了兩次,不符合,返回false
                if (map.get(sChar) != tChar) {
                    return false;
                }
            }
        }
        return true;
    }
}
相關文章
相關標籤/搜索