Skip to content

Commit eaf8d38

Browse files
authored
Merge pull request neetcode-gh#1440 from Mahim1997/dev/205_Java_Swift
205. Isomorphic Strings
2 parents fb5b707 + f6e4521 commit eaf8d38

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

java/205-Isomorphic-Strings.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
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+
}

swift/205-Isomorphic-Strings.swift

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
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+
}

0 commit comments

Comments
 (0)