Skip to content

Commit

Permalink
205. Isomorphic Strings
Browse files Browse the repository at this point in the history
  • Loading branch information
Mahim1997 committed Nov 7, 2022
1 parent 3cfb9a5 commit f6e4521
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
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
}
}

0 comments on commit f6e4521

Please sign in to comment.