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
Example 2:
Input: s = "foo", t = "bar" Output: false
Example 3:
Input: s = "paper", t = "title" Output: true
Constraints:
1 <= s.length <= 5 * 10^4
t.length == s.length
s
andt
consist of any valid ascii character.
【C++】
class Solution {
public:
bool isIsomorphic(string s, string t) {
vector<int> s_first_index(256, 0), t_first_index(256, 0);
for (int i = 0; i < s.length(); ++i) {
if (s_first_index[s[i]] != t_first_index[t[i]]) {
return false;
}
s_first_index[s[i]] = t_first_index[t[i]] = i + 1;
}
return true;
}
};
【Java】
class Solution {
public boolean isIsomorphic(String s, String t) {
int[] s_first_index = new int[256];
Arrays.fill(s_first_index, 0);
int[] t_first_index = new int[256];
Arrays.fill(t_first_index, 0);
for (int i = 0; i < s.length(); ++i) {
if (s_first_index[s.charAt(i)] != t_first_index[t.charAt(i)]) {
return false;
}
s_first_index[s.charAt(i)] = t_first_index[t.charAt(i)] = i + 1;
}
return true;
}
}