Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions java/205-Isomorphic-Strings.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
class Solution {
public boolean isIsomorphic(String s, String t) {
// Needs bidirectional mapping from s <--> t
if(s.length() != t.length()) {
return false;
}

Map<Character, Character> mapSourceToDest = new HashMap<>();
Map<Character, Character> mapDestToSource = new HashMap<>();

int len = s.length();
for(int i=0; i<len; i++) {
char sourceChar = s.charAt(i), destChar = t.charAt(i);
char sourceReturn = mapSourceToDest.getOrDefault(sourceChar, destChar);
if(sourceReturn != destChar) {
return false;
}
mapSourceToDest.put(sourceChar, destChar);

char destReturn = mapDestToSource.getOrDefault(destChar, sourceChar);
if(destReturn != sourceChar) {
return false;
}
mapDestToSource.put(destChar, sourceChar);
}

return true;
}
}
24 changes: 24 additions & 0 deletions swift/205-Isomorphic-Strings.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
class Solution {
func isIsomorphic(_ s: String, _ t: String) -> Bool {
guard s.count == t.count else { return false }

var mapSourceToDest: [Character: Character] = [:]
var mapDestToSource: [Character: Character] = [:]

for (sourceChar, destChar) in zip(s, t) {
if let sourceMapped = mapSourceToDest[sourceChar] {
guard sourceMapped == destChar else { return false }
} else {
mapSourceToDest[sourceChar] = destChar
}

if let destMapped = mapDestToSource[destChar] {
guard destMapped == sourceChar else { return false }
} else {
mapDestToSource[destChar] = sourceChar
}
}

return true
}
}