Skip to content

Commit b25e88f

Browse files
committed
solve isomorphic-strings.js
1 parent 74f2b42 commit b25e88f

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

isomorphic-strings.js

+58
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/**
2+
* Source: https://leetcode.com/problems/isomorphic-strings/
3+
* Tags: [Hash Table]
4+
* Level: Easy
5+
* Title: Isomorphic Strings
6+
* Auther: @imcoddy
7+
* Content: Given two strings s and t, determine if they are isomorphic.
8+
*
9+
* Two strings are isomorphic if the characters in s can be replaced to get t.
10+
*
11+
* 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.
12+
*
13+
* For example,
14+
* Given "egg", "add", return true.
15+
*
16+
* Given "foo", "bar", return false.
17+
*
18+
* Given "paper", "title", return true.
19+
*
20+
* Note:
21+
* You may assume both s and t have the same length.
22+
*/
23+
24+
/**
25+
* @param {string} s
26+
* @param {string} t
27+
* @return {boolean}
28+
*/
29+
30+
/**
31+
* Memo:
32+
* Runtime: 133ms
33+
* Rank: A
34+
*/
35+
var isIsomorphic = function(s, t) {
36+
var map_s = {};
37+
var map_t = {};
38+
var result = true;
39+
for (var i = 0; i < s.length; i++) {
40+
if (map_s[s[i]] || map_t[t[i]]) {
41+
if (map_s[s[i]] !== t[i] || map_t[t[i]] !== s[i]) {
42+
result = false;
43+
break;
44+
}
45+
} else {
46+
map_s[s[i]] = t[i];
47+
map_t[t[i]] = s[i];
48+
}
49+
}
50+
51+
return result;
52+
};
53+
54+
console.log(isIsomorphic('egg', 'add'));
55+
console.log(isIsomorphic('foo', 'bar'));
56+
console.log(isIsomorphic('paper', 'title'));
57+
console.log(isIsomorphic('ab', 'ca'));
58+
console.log(isIsomorphic('ab', 'aa'));

0 commit comments

Comments
 (0)