Baozi Leetcode Solution 205: Isomorphic Strings

时间:2023-03-09 16:15:53
Baozi Leetcode Solution 205: Isomorphic Strings

Problem Statement

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 and have the same length.

Problem link

Video Tutorial

You can find the detailed video tutorial here

Thought Process

A relatively straightforward problem, very similar to Word Pattern. All we have to do is check the one to one mapping from string a to string b, also it needs to maintain a bijection mapping (meaning no two different characters in a should map to the same character in b)

Use bijection mapping

Check character one by one from a and b. If char in a hasn't been seen before, create a one to one mapping between this char in a and the char in b so later if this char in a is seen again, it has to map to b, else we return false. Moreover, need to make sure the char in b is never mapped by a different character.

Baozi Leetcode Solution 205: Isomorphic Strings

An explanation int the video

Solutions

 public boolean isIsomorphic(String a, String b) {
if (a == null || b == null || a.length() != b.length()) {
return false;
}
Map<Character, Character> lookup = new HashMap<>();
Set<Character> dupSet = new HashSet<>(); for (int i = 0; i < a.length(); i++) {
char c1 = a.charAt(i);
char c2 = b.charAt(i); if (lookup.containsKey(c1)) {
if (c2 != lookup.get(c1)) {
return false;
}
} else {
lookup.put(c1, c2);
// this to prevent different c1s map to the same c2, it has to be a bijection mapping
if (dupSet.contains(c2)) {
return false;
}
dupSet.add(c2);
}
}
return true;
}

Time Complexity: O(N), N is the length of string a or string b

Space Complexity: O(N), N is the length of string a or string b because the hashmap and set we use

References