LeetCode 205. Isomorphic Strings
Given two strings s
and t
, determine if they are isomorphic.
Two strings s and t 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
method
注意:数组要给个数,不然会随机初始化
int a[3];
// 2147 3181 -976355383 都是随机的
int a[3] = {1};
// 1 0 0 第一个元素有赋值,其他初始化为0
用一个长度为256
的数组记录每个字符上一次出现的位置
如果两个字符上一次出现的位置相同,就更新为这一次的位置,继续
否则直接返回false
因为数组初始化为0
,所以下标的位置就从1
开始,不然第一个元素的位置会赋值为i=0
,就跟初始化一样了
bool isIsomorphic(string s, string t) {
int preS[256] = {0}; // 给个第一个元素,其他初始化为0
int preT[256] = {0};
for (int i = 0; i < s.size(); ++i) {
if (preS[int(s[i])] != preT[int(t[i])]) return false;
preS[int(s[i])] = i + 1; // 更新出现位置
preT[int(t[i])] = i + 1; // 下标从1开始
}
return true;
}