205. Isomorphic Strings (Easy)
https://leetcode.com/problems/isomorphic-strings/
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.
Solutions
class Solution {
public boolean isIsomorphic(String s, String t) {
if (s == null || t == null) {
return false;
}
int len = s.length();
// Used to keep the distribution of different chars.
Map<Character, List<Integer>> map1 = new HashMap<>();
Map<Character, List<Integer>> map2 = new HashMap<>();
for (int i = 0; i < len; i++) {
if (!map1.containsKey(s.charAt(i))) {
map1.put(s.charAt(i), new ArrayList<>());
}
map1.get(s.charAt(i)).add(i);
}
for (int i = 0; i < len; i++) {
if (!map2.containsKey(t.charAt(i))) {
map2.put(t.charAt(i), new ArrayList<>());
}
map2.get(t.charAt(i)).add(i);
}
Set<Character> visited = new HashSet<>();
for (int i = 0; i < len; i++) {
// Important, ignore visited char's distribution to save up time
if (visited.contains(s.charAt(i))) {
continue;
}
String idx1 = map1.get(s.charAt(i)).toString();
String idx2 = map2.get(t.charAt(i)).toString();
if (!idx1.equals(idx2)) {
return false;
}
visited.add(s.charAt(i));
}
return true;
}
}
Incorrect Solutions
class Solution {
// Time Limit Exceeded
public boolean isIsomorphic(String s, String t) {
if (s == null || t == null) {
return false;
}
int len = s.length();
for (int i = 0; i < len; i++) {
for (int j = i + 1; j < len; j++) {
if (s.charAt(i) == s.charAt(j) && t.charAt(i) != t.charAt(j)) {
return false;
}
if (s.charAt(i) != s.charAt(j) && t.charAt(i) == t.charAt(j)) {
return false;
}
}
}
return true;
}
}