原題地址
https://leetcode.com/problems/isomorphic-strings/
題目描述
Given two strings s and t, determine if they are isomorphic.
給出兩個字符串s和t,判斷它們是否是同構的。
Two strings are isomorphic if the characters in s can be replaced to get t.
如果可以通過替換s中的字符來得到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.
同一個字符只能替換成另外一個字符,且兩個字符不能映射成同一個字符,但是字符可以映射爲自身(也就是沒有替換)。
For example,
例如,
Given,
給出
s = "egg", t = "add", return true.
s = "foo", t = "bar", return false.
s = "paper", t = "title", return true.
Tags Hash Table
解題思路
這個題比較簡單,嘗試將s[i]替換爲t[i],記錄一些從s中的字符替換到t之後的映射以及t中字符對s中字符的映射,然後在嘗試替換時看與之前的映射是否有衝突即可。詳見代碼。
另外需要注意的是,一個字符爲8位,大小界於0~255之間。
代碼
/** 判斷兩個字符串是否同構 */
bool isIsomorphic(char* s, char* t) {
int len = strlen(s);
if (len != strlen(t)) return false;
// mapTo表示s中的某種字符替換到t之後的字符
// mapFrom表示t中的某種字符替換到s之後字符
int mapTo[256], mapFrom[256];
// 初始化爲-1
int i = -1;
while (++i < 256) mapTo[i] = mapFrom[i] = -1;
i = 0;
char from, to;
while (i < len) {
from = *(s + i);
to = *(t + i);
// 如果兩個字符都沒有做過替換
if (mapTo[from] == -1 && mapFrom[to] == -1) {
mapTo[from] = to; // 替換並記錄兩個字符的映射
mapFrom[to] = from;
} else {
// 如果兩個字符中有一個做過映射,且與當前映射情況不符,返回false
if (mapTo[from] != -1 && mapTo[from] != to)
return false;
if (mapFrom[to] != -1 && mapFrom[to] != from)
return false;
}
++i;
}
return true;
}
完整代碼 https://github.com/Orange1991/leetcode/blob/master/205/c/main.c
測試數據
s = egg,
t = add,
they are isomorphic.
s = foo,
t = bar,
they are not isomorphic.
s = paper,
t = title,
they are isomorphic.
s = a,
t = a,
they are isomorphic.
s = ab,
t = ab,
they are isomorphic.
s = 13,
t = 42,
they are isomorphic.
2015/8/7