1. 程式人生 > >leetcode:(205) Isomorphic Strings(java)

leetcode:(205) Isomorphic Strings(java)

package LeetCode_HashTable;

/**
 * 題目:
 *      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
 *      Note:You may assume both s and t have the same length.
 * 解題思路:
 *      把s中的字元作為鍵,t中的字元作為鍵值,用雜湊表簡歷對映關係。
 *      如果雜湊表中沒有temp1這個鍵,同時也沒有temp2這個鍵值,那麼將temp1,temp2加入到雜湊表中,
 *      若沒有temp1,有temp2,不滿足同構條件,返回false.
 *      如果雜湊表中有temp1這個鍵,並且temp1的鍵值等於temp2,則進行下一次迴圈。
 *      若雜湊表中有temp1這個鍵,但是temp1鍵值不等於temp2,不滿足同構條件,返回false.
 */

import java.util.HashMap;
public class IsIsomorphic_205_1021 {
    public boolean IsIsomorphic(String s, String t) {
        if (s == null || s.length() == 0) {
            return true;
        }
        if (s.length() != t.length()) {
            return false;
        }

        HashMap<Character, Character> map = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            char temp1 = s.charAt(i);
            char temp2 = t.charAt(i);


            if (!map.containsKey(temp1)) {
                if (!map.containsValue(temp2)) {
                    map.put(temp1, temp2);
                    continue;
                } else return false;
            }
            else {
                if (map.get(temp1) == temp2) {
                    continue;
                } else {
                    return false;
                }
            }
        }
        return true;
    }

    public static void main(String[] args) {
        String s = "aba";
        String t = "baa";

        IsIsomorphic_205_1021 test = new IsIsomorphic_205_1021();
        boolean result = test.IsIsomorphic(s, t);
        System.out.println(result);
    }
}