【EASY】Isomorphic Strings

# 问题

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.``````

Note:

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

# 分析过程

• 输入：两个长度相同的字符串
• 输出：两个字符串是否是同构的字符串
• 思路：使用两个 map 用来记录某个字符出现的索引，遍历字符串时判断当前遍历的字符在 map 中记录的索引是否相同，如果不同直接返回 false。

# 解决方法

``````class Solution {
public:
bool isIsomorphic(string s, string t) {
const char *a = s.c_str();
const char *b = t.c_str();

map<char, int> mapA, mapB;

int len = (int)strlen(a);

for (int i = 0; i < len; i++) {
if (mapA[a[i]] != mapB[b[i]]) {
return false;
}
// 使用i+1避免和原始的0重复
mapA[a[i]] = i + 1;
mapB[b[i]] = i + 1;
}

return true;
}
};``````