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.
For example,
Given "egg"
, "add"
, return true.
Given "foo"
, "bar"
, return false.
Given "paper"
, "title"
, return true.
Note:
You may assume both s and t have the same length.
【解题思路】
返回true需要满足两个条件:
1、不能出现s中的一个字符对应到t中两个不同的字符
2、不能出现s中的两个不同字符对应到t中同一个字符
彼此之间映射关系不能错。
先贴个自己犯错的错误代码,关于memset错误用法。
//Isomorphic Strings //Written by ZP1015 //2015.11.16 bool isIsomorphic(char* s, char* t) { if(!s||!t) return false; int slen = strlen(s); int tlen = strlen(t); int i = 0; if(slen!=tlen) return false; int *sTotTable = (int *)malloc(sizeof(int)*256); int *tTosTable = (int *)malloc(sizeof(int)*256); memset(sTotTable, -1, sizeof(int)*256); //存在严重问题 memset(tTosTable, -1, sizeof(int)*256); for(i=0;i<slen;i++) { if(sTotTable[s[i]] == -1) { if(tTosTable[t[i]] == -1) { sTotTable[s[i]] = t[i]; /*s->t 转换关系*/ tTosTable[t[i]] = s[i]; /*t->s 转换关系*/ } else { goto NotIsomorphic; } } else { if(sTotTable[s[i]]!= t[i]) goto NotIsomorphic; } } free(sTotTable); free(tTosTable); return true; NotIsomorphic: free(sTotTable); free(tTosTable); return false; }
<pre name="code" class="cpp">//Isomorphic Strings //Written by ZP1015 //2015.11.16 bool isIsomorphic(char* s, char* t) { if(!s||!t) return false; int slen = strlen(s); int tlen = strlen(t); int i = 0; if(slen!=tlen) return false; int sTotTable[256]; int tTosTable[256]; for(i=0;i<256;i++) { sTotTable[i] = -1; tTosTable[i] = -1; } for(i=0;i<slen;i++) { if(sTotTable[s[i]] == -1) { if(tTosTable[t[i]] == -1) { sTotTable[s[i]] = t[i]; /*s->t 转换关系*/ tTosTable[t[i]] = s[i]; /*t->s 转换关系*/ } else { return false; } } else { if(sTotTable[s[i]]!= t[i]) return false; } } return true; }