Skip to content

Commit 83920a7

Browse files
committed
205. Isomorphic Strings
1 parent 8b0dec6 commit 83920a7

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@
4141
| 121 | Best Time to Buy and Sell Stock | [Ruby](./algorithms/ruby/0121-best-time-to-buy-and-sell-stock.rb) | Easy |
4242
| 129 | Sum Root to Leaf Numbers | [Ruby](./algorithms/ruby/0129-sum-root-to-leaf-numbers.rb) | Medium |
4343
| 142 | Linked List Cycle II | [Ruby](./algorithms/ruby/0142-linked-list-cycle-ii.rb) | Medium |
44+
| 205 | Isomorphic Strings | [Ruby](./algorithms/ruby/0205-isomorphic-strings.rb) | Easy |
4445
| 208 | Implement Trie (Prefix Tree) | [Ruby](./algorithms/ruby/0208-implement-trie-prefix-tree.rb) | Medium |
4546
| 211 | Design Add and Search Words Data Structure | [Ruby](./algorithms/ruby/0211-design-add-and-search-words-data-structure.rb) | Medium |
4647
| 226 | Invert Binary Tree | [Ruby](./algorithms/ruby/0226-invert-binary-tree.rb) | Easy |
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
# frozen_string_literal: true
2+
3+
# 205. Isomorphic Strings
4+
# https://leetcode.com/problems/isomorphic-strings
5+
6+
=begin
7+
8+
Given two strings s and t, determine if they are isomorphic.
9+
10+
Two strings s and t are isomorphic if the characters in s can be replaced to get t.
11+
12+
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.
13+
14+
### Example 1:
15+
16+
Input: s = "egg", t = "add"
17+
Output: true
18+
19+
### Example 2:
20+
21+
Input: s = "foo", t = "bar"
22+
Output: false
23+
24+
### Example 3:
25+
26+
Input: s = "paper", t = "title"
27+
Output: true
28+
29+
### Constraints:
30+
31+
* 1 <= s.length <= 5 * 104
32+
* t.length == s.length
33+
* s and t consist of any valid ascii character.
34+
35+
=end
36+
37+
# Runtime 258 ms
38+
# Memory 211.3 MB
39+
# @param {String} s
40+
# @param {String} t
41+
# @return {Boolean}
42+
def is_isomorphic(s, t)
43+
ms = {}
44+
mt = {}
45+
n = s.length
46+
i = 0
47+
48+
while i < n && ms[s[i]] == mt[t[i]]
49+
ms[s[i]] = mt[t[i]] = i + 1
50+
i += 1
51+
end
52+
53+
i == n
54+
end
55+
56+
# **************** #
57+
# TEST #
58+
# **************** #
59+
60+
require "test/unit"
61+
class Test_is_isomorphic < Test::Unit::TestCase
62+
def test_
63+
assert_equal true, is_isomorphic("egg", "add")
64+
assert_equal false, is_isomorphic("foo", "bar")
65+
assert_equal true, is_isomorphic("paper", "title")
66+
end
67+
end

0 commit comments

Comments
 (0)