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

猜你喜欢

转载自blog.csdn.net/Sunshine_liang1/article/details/83244886