|
| 1 | +# [205. 同构字符串](https://leetcode-cn.com/problems/isomorphic-strings/description/) |
| 2 | + |
| 3 | +### 题目描述 |
| 4 | + |
| 5 | +<p>给定两个字符串 <em><strong>s </strong></em>和 <strong><em>t</em></strong>,判断它们是否是同构的。</p> |
| 6 | + |
| 7 | +<p>如果 <em><strong>s </strong></em>中的字符可以被替换得到 <strong><em>t </em></strong>,那么这两个字符串是同构的。</p> |
| 8 | + |
| 9 | +<p>所有出现的字符都必须用另一个字符替换,同时保留字符的顺序。两个字符不能映射到同一个字符上,但字符可以映射自己本身。</p> |
| 10 | + |
| 11 | +<p><strong>示例 1:</strong></p> |
| 12 | + |
| 13 | +<pre><strong>输入:</strong> <strong><em>s</em></strong> = <code>"egg", </code><strong><em>t = </em></strong><code>"add"</code> |
| 14 | +<strong>输出:</strong> true |
| 15 | +</pre> |
| 16 | + |
| 17 | +<p><strong>示例 2:</strong></p> |
| 18 | + |
| 19 | +<pre><strong>输入:</strong> <strong><em>s</em></strong> = <code>"foo", </code><strong><em>t = </em></strong><code>"bar"</code> |
| 20 | +<strong>输出:</strong> false</pre> |
| 21 | + |
| 22 | +<p><strong>示例 3:</strong></p> |
| 23 | + |
| 24 | +<pre><strong>输入:</strong> <strong><em>s</em></strong> = <code>"paper", </code><strong><em>t = </em></strong><code>"title"</code> |
| 25 | +<strong>输出:</strong> true</pre> |
| 26 | + |
| 27 | +<p><strong>说明:</strong><br> |
| 28 | +你可以假设 <em><strong>s </strong></em>和 <strong><em>t </em></strong>具有相同的长度。</p> |
| 29 | + |
| 30 | +### 解题思路 |
| 31 | + |
| 32 | + |
| 33 | +### 具体解法 |
| 34 | + |
| 35 | +1. 设置`s`和`t`的`hash table` |
| 36 | +2. 遍历随意一个字符串 |
| 37 | +3. 将遍历到的字符串的当作`key`, 字符串下标 `i+1` 当作`value`保存在`map`中 |
| 38 | +4. 判断`map`中相同下标的字符串的对应下标位置是否相同 |
| 39 | + |
| 40 | +#### **Golang** |
| 41 | +```go |
| 42 | +func isIsomorphic(s string, t string) bool { |
| 43 | + sMap, tMap := map[uint8]int{}, map[uint8]int{} |
| 44 | + for i := range s { |
| 45 | + if sMap[s[i]] != tMap[t[i]] { |
| 46 | + return false |
| 47 | + } else { |
| 48 | + sMap[s[i]] = i + 1 |
| 49 | + tMap[t[i]] = i + 1 |
| 50 | + } |
| 51 | + } |
| 52 | + return true |
| 53 | +} |
| 54 | +``` |
| 55 | + |
| 56 | + |
0 commit comments