Skip to content

Commit 601a741

Browse files
committed
Added: isIsomorphic strings
1 parent 39345b2 commit 601a741

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

README.md

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -276,6 +276,51 @@
276276
```
277277
**View on Codepen:** http://codepen.io/kennymkchan/pen/xgNNNB?editors=0012
278278

279+
<a name="string--isIsomorphic"></a><a name="2.3"></a>
280+
- **[2.3](#string--palindrome) Check if a given string is a isomorphic**
281+
282+
```
283+
For two strings to be isomorphic, all occurrences of a character in string A can be replaced with another character
284+
to get string B. The order of the characters must be preserved. There must be one-to-one mapping for ever char of
285+
string A to every char of string B.
286+
287+
`paper` and `title` would return true.
288+
`egg` and `sad` would return false.
289+
`dgg` and `add` would return true.
290+
```
291+
```javascript
292+
isIsomorphic("egg", 'add'); // true
293+
isIsomorphic("paper", 'title'); // true
294+
isIsomorphic("kick", 'side'); // false
295+
296+
function isIsomorphic(firstString, secondString) {
297+
298+
// Check if the same lenght. If not, they cannot be isomorphic
299+
if (firstString.length !== secondString.length) return false
300+
301+
var letterMap = {};
302+
303+
for (var i = 0; i < firstString.length; i++) {
304+
var letterA = firstString[i],
305+
letterB = secondString[i];
306+
307+
// If the letter does not exist, create a map and map it to the value
308+
// of the second letter
309+
if (letterMap[letterA] === undefined) {
310+
letterMap[letterA] = letterB;
311+
} else if (letterMap[letterA] !== letterB) {
312+
// Eles if letterA already exists in the map, but it does not map to
313+
// letterB, that means that A is mapping to more than one letter.
314+
return false;
315+
}
316+
}
317+
// If after iterating through and conditions are satisfied, return true.
318+
// They are isomorphic
319+
return true;
320+
}
321+
```
322+
**View on Codepen:** http://codepen.io/kennymkchan/pen/mRZgaj?editors=0012
323+
279324
**[⬆ back to top](#table-of-contents)**
280325
281326
## Stacks and Queues

0 commit comments

Comments
 (0)