题目
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的映射,只能一一对应。在C语言中是没有类似于HaspMap、Dictionary这样的数据结构,但是可以使用数组进行实现。由于string中的每个character都在0-255之间,为可打印字符,因此,使用数组对其进行map是最合适不过的。
声明hashArr对字符进行映射。
int* hashArr = (int*)malloc(sizeof(int) * 255);
for (int i = 0; i < 255; ++i) // initialize
hashArr[i] = 0;
在遍历过程中,有两种情况:
- hashArr[s[i]]为0,即s[i]在hashArr中还没有被映射,此时如果遍历hashArr找到了一个映射和t[i]相等,则return false;
- hashArr[s[i]]不为0,即s[i]已经被映射,如果hashArr[s[i]]和t[i]不相等,则是不允许的,这样也return false。
另外需要注意的是,循环不要使用strlen(s),这样在提交后会导致“Time Limit Exceeded”,应使用判断s[i] != '\0'。
代码(C语言)
bool isIsomorphic(char* s, char* t) {
int* hashArr = (int*)malloc(sizeof(int) * 255);
// initialize
for (int i = 0; i < 255; ++i)
hashArr[i] = 0;
for (int i = 0; s[i] != '\0'; ++i) { // Don't use strlen(s)
int index = s[i];
if (hashArr[index] == 0) {
for (int j = 0; j < 255; ++j) {
if (hashArr[j] == t[i])
return false;
}
hashArr[index] = t[i];
} else {
if (hashArr[index] != t[i])
return false;
}
}
free(hashArr);
return true;
}
网友评论