TheAlgorithms-Ruby/data_structures/hash_table/isomorphic_strings.rb

65 lines
1.6 KiB
Ruby
Raw Permalink Normal View History

2021-06-16 01:09:38 +02:00
# Challenge name: Isomorphic Strings
#
# 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.
2021-09-03 22:24:58 +02:00
# All occurrences of a character must be replaced with another character while preserving the order of characters.
2021-06-16 01:09:38 +02:00
# 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 * 104
# t.length == s.length
# s and t consist of any valid ascii character.
2021-06-22 23:31:04 +02:00
# Approach 1: Hash Map
# Time Complexity: O(N)
2021-07-02 22:54:01 +02:00
# Space Complexity: O(N)
2021-06-22 23:31:04 +02:00
def isomorphic_strings_check(s, t)
# store character mappings
map = {}
# store already mapped characters
set = []
(0..s.length - 1).each do |i|
# store characters to compare
char1 = s[i]
char2 = t[i]
# if char1 is mapped
2021-09-03 22:24:58 +02:00
if map[char1]
2021-06-22 23:31:04 +02:00
# return false if char1 is mapped to a different character than already present
return false if map[char1] != char2
# if char1 is not mapped
else
# return false if char2 is already mapped to a different character
return false if set.include?(char2)
2021-09-03 22:24:58 +02:00
2021-06-22 23:31:04 +02:00
# checks passed: add new character map and track that char2 has been mapped
map[char1] = char2
set << char2
end
end
2021-09-03 22:24:58 +02:00
true
2021-06-22 23:31:04 +02:00
end
2021-09-03 22:24:58 +02:00
puts isomorphic_strings_check('egg', 'add')
2021-06-22 23:31:04 +02:00
# => true
2021-09-03 22:24:58 +02:00
puts isomorphic_strings_check('foo', 'bar')
2021-06-22 23:31:04 +02:00
# => false
2021-09-03 22:24:58 +02:00
puts isomorphic_strings_check('paper', 'title')
2021-07-02 22:54:01 +02:00
# => true