|
| 1 | +# Challenge name: Isomorphic Strings |
| 2 | +# |
| 3 | +# Given two strings s and t, determine if they are isomorphic. |
| 4 | +# Two strings s and t are isomorphic if the characters in s can be replaced to get t. |
| 5 | +# All occurrences of a character must be replaced with another character while preserving the order of characters. |
| 6 | +# No two characters may map to the same character, but a character may map to itself. |
| 7 | +# |
| 8 | +# Example 1: |
| 9 | +# Input: s = "egg", t = "add" |
| 10 | +# Output: true |
| 11 | +# |
| 12 | +# Example 2: |
| 13 | +# Input: s = "foo", t = "bar" |
| 14 | +# Output: false |
| 15 | +# |
| 16 | +# Example 3: |
| 17 | +# Input: s = "paper", t = "title" |
| 18 | +# Output: true |
| 19 | +# |
| 20 | +# Constraints: |
| 21 | +# 1 <= s.length <= 5 * 104 |
| 22 | +# t.length == s.length |
| 23 | +# s and t consist of any valid ascii character. |
| 24 | + |
| 25 | +# Approach 1: Hash Map |
| 26 | +# Time Complexity: O(N) |
| 27 | +# Space Complexity: O(N) |
| 28 | + |
| 29 | +def isomorphic_strings_check(s, t) |
| 30 | + # store character mappings |
| 31 | + map = {} |
| 32 | + # store already mapped characters |
| 33 | + set = [] |
| 34 | + |
| 35 | + (0..s.length - 1).each do |i| |
| 36 | + # store characters to compare |
| 37 | + char1 = s[i] |
| 38 | + char2 = t[i] |
| 39 | + |
| 40 | + # if char1 is mapped |
| 41 | + if map[char1] |
| 42 | + # return false if char1 is mapped to a different character than already present |
| 43 | + return false if map[char1] != char2 |
| 44 | + # if char1 is not mapped |
| 45 | + else |
| 46 | + # return false if char2 is already mapped to a different character |
| 47 | + return false if set.include?(char2) |
| 48 | + # checks passed: add new character map and track that char2 has been mapped |
| 49 | + map[char1] = char2 |
| 50 | + set << char2 |
| 51 | + end |
| 52 | + |
| 53 | + end |
| 54 | + return true |
| 55 | +end |
| 56 | + |
| 57 | +puts isomorphic_strings_check("egg", "add") |
| 58 | +# => true |
| 59 | + |
| 60 | +puts isomorphic_strings_check("foo", "bar") |
| 61 | +# => false |
| 62 | + |
| 63 | +puts isomorphic_strings_check("paper", "title") |
| 64 | +# => true |
0 commit comments