File tree Expand file tree Collapse file tree 2 files changed +53
-0
lines changed Expand file tree Collapse file tree 2 files changed +53
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public boolean isIsomorphic (String s , String t ) {
3
+ // Needs bidirectional mapping from s <--> t
4
+ if (s .length () != t .length ()) {
5
+ return false ;
6
+ }
7
+
8
+ Map <Character , Character > mapSourceToDest = new HashMap <>();
9
+ Map <Character , Character > mapDestToSource = new HashMap <>();
10
+
11
+ int len = s .length ();
12
+ for (int i =0 ; i <len ; i ++) {
13
+ char sourceChar = s .charAt (i ), destChar = t .charAt (i );
14
+ char sourceReturn = mapSourceToDest .getOrDefault (sourceChar , destChar );
15
+ if (sourceReturn != destChar ) {
16
+ return false ;
17
+ }
18
+ mapSourceToDest .put (sourceChar , destChar );
19
+
20
+ char destReturn = mapDestToSource .getOrDefault (destChar , sourceChar );
21
+ if (destReturn != sourceChar ) {
22
+ return false ;
23
+ }
24
+ mapDestToSource .put (destChar , sourceChar );
25
+ }
26
+
27
+ return true ;
28
+ }
29
+ }
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ func isIsomorphic( _ s: String , _ t: String ) -> Bool {
3
+ guard s. count == t. count else { return false }
4
+
5
+ var mapSourceToDest : [ Character : Character ] = [ : ]
6
+ var mapDestToSource : [ Character : Character ] = [ : ]
7
+
8
+ for (sourceChar, destChar) in zip ( s, t) {
9
+ if let sourceMapped = mapSourceToDest [ sourceChar] {
10
+ guard sourceMapped == destChar else { return false }
11
+ } else {
12
+ mapSourceToDest [ sourceChar] = destChar
13
+ }
14
+
15
+ if let destMapped = mapDestToSource [ destChar] {
16
+ guard destMapped == sourceChar else { return false }
17
+ } else {
18
+ mapDestToSource [ destChar] = sourceChar
19
+ }
20
+ }
21
+
22
+ return true
23
+ }
24
+ }
You can’t perform that action at this time.
0 commit comments