205. Isomorphic Strings
Question:
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:
Input: s = "egg", t = "add"
Output: true
Input: s = "foo", t = "bar"
Output: false
Input: s = "paper", t = "title"
Output: true
Source code
Version 1
Idea:
"Isomorphic" means that no more than one character of string can map to the same character. E.g., s1="apple"
s2="paper"
, you can see two p alphabets of s1 map to a alphabet and p alphabet at s2, the result is false.
Hence, you need to record each character relationship (two strings) to unordered map container.
At 8-16 line, you should through all characters. If this character isn't exist in unmap_s
and unmap_t
, store a character of the other side. At 10 line, if a character isn't exist in unmap_s
but it has already exist in numap_t
, it means more than one character map to the same character, so return false.
At 13 line, if this character has already exist in unmap_s
, you can get the value (=previous t[i]) then you find the value isn't equal to current t[i], return false.
1 | class Solution { |
Version 2
Idea:
This strategy uses only one unordered map container. But I implemented a matchbyValue
function to check value existence in container.
1 | class Solution { |
Version 3
Idea:
It is an optimal approach that refered to online.
Initial two array to zero at first. At 10-11 line, store the position of character, i + 1
means the range of value is 1 to n, because inital value of array is zero.
So, if the values are not equal between map_s and map_t, return false. It represented characters are shown in different position. (characters are the same alphabet.)
1 | class Solution { |