# 638.Strings Homomorphism

## 1.Description(Easy)

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.

### Notice

You may assume both s and t have the`same length`.

**Example**

Given s =`"egg"`, t =`"add"`, return`true`.

Given s =`"foo"`, t =`"bar"`, return`false`.

Given s =`"paper"`, t =`"title"`, return`true`.

[**Tags**](http://www.lintcode.com/en/problem/strings-homomorphism/#tags)

[LinkedIn](http://www.lintcode.com/tag/linkedin/) [Hash Table](http://www.lintcode.com/tag/hash-table/)

## 2.Code

Solution 1:

判断对应位置字符是否成唯一映射，同时判断是否出现重复映射。

```
public boolean isIsomorphic(String s, String t) {
        if(s.length()!=t.length()){
            return false;
        }
        HashMap<Character,Character> map=new HashMap<Character,Character>();
        HashSet<Character> set=new HashSet<Character>();
        for(int i=0;i<s.length();i++){
            if(!map.containsKey(s.charAt(i))){
                //如果map中没有s的值，但是set中已经出现了，就说明出现了重复映射。
                if(set.contains(t.charAt(i))){
                    return false;
                }
                map.put(s.charAt(i),t.charAt(i));
                set.add(t.charAt(i));
            }
            else{
                if(map.get(s.charAt(i))!=t.charAt(i)){
                    return false;
                }
            }
        }
        return true;
    }
```

Solution 2:

```
public boolean isIsomorphic(String s, String t) {
        // Write your code here
        int[] m1 = new int[128];
        int[] m2 = new int[128];
        for (int i = 0; i < s.length(); ++i) {
            int cs = (int) s.charAt(i);
            int ts = (int) t.charAt(i);
            if (m1[cs] == 0 && m2[ts] == 0) {
                m1[cs] = ts;
                m2[ts] = 1;
            } else if (m1[cs] != ts) {
                return false;
            }
        }
        return true;
    }
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://junnie.gitbook.io/nine-chapter/8.data-structure/638strings-homomorphism.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
