问题:
难度:easy
说明:
比较下两个字符串是不是同构的,就是两个字符串,如果不一定完全一致,但是构造形式相似就行。
题目连接:https://leetcode.com/problems/isomorphic-strings/
输入范围:
1 <= s.length <= 5 * 104
t.length == s.length
s
andt
consist of any valid ascii character.
输入案例:
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
我的代码:
加一个双向的映射 Map 即可,要注意是256的长度,因为输入是所有 ascii 的编码字符。
Java:
class Solution {
public boolean isIsomorphic(String s, String t) {
int lens = s.length(), lent = t.length();
if(lens != lent) return false;
char[] chs = s.toCharArray(), cht = t.toCharArray();
int mapStoT[] = new int[256], mapTtoS[] = new int[256];
Arrays.fill(mapStoT, -1);
Arrays.fill(mapTtoS, -1);
for(int i = 0; i < lens; i ++) {
int ts = (int)chs[i], tt = (int)cht[i];
if(mapStoT[ts] == -1 && mapTtoS[tt] == -1) {
mapStoT[ts] = tt;
mapTtoS[tt] = ts;
} else {
if(mapStoT[ts] != tt || mapTtoS[tt] != ts) return false;
}
}
return true;
}
}
C++:
class Solution {
public:
bool isIsomorphic(string s, string t) {
int lens = s.length(), lent = t.length();
if(lens != lent) return false;
int mapStoT[256], mapTtoS[256];
memset(mapStoT, -1, sizeof(mapStoT)), memset(mapTtoS, -1, sizeof(mapTtoS));
for(int i = 0; i < lens; i ++) {
int ts = (int)s[i], tt = (int)t[i];
if(mapStoT[ts] == -1 && mapTtoS[tt] == -1) {
mapStoT[ts] = tt;
mapTtoS[tt] = ts;
} else if(mapStoT[ts] != tt || mapTtoS[tt] != ts) return false;
}
return true;
}
};