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
43 changes: 31 additions & 12 deletions src/main/java/com/thealgorithms/strings/Isomorphic.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,35 +5,54 @@
import java.util.Map;
import java.util.Set;

/**
* Utility class to check if two strings are isomorphic.
*
* <p>
* Two strings {@code s} and {@code t} are isomorphic if the characters in {@code s}
* can be replaced to get {@code t}, while preserving the order of characters.
* Each character must map to exactly one character, and no two characters can map to the same character.
* </p>
*
* @see <a href="https://en.wikipedia.org/wiki/Isomorphism_(computer_science)">Isomorphic Strings</a>
*/
public final class Isomorphic {

private Isomorphic() {
}

public static boolean checkStrings(String s, String t) {
/**
* Checks if two strings are isomorphic.
*
* @param s the first input string
* @param t the second input string
* @return {@code true} if {@code s} and {@code t} are isomorphic; {@code false} otherwise
*/
public static boolean areIsomorphic(String s, String t) {
if (s.length() != t.length()) {
return false;
}

// To mark the characters of string using MAP
// character of first string as KEY and another as VALUE
// now check occurence by keeping the track with SET data structure
Map<Character, Character> characterMap = new HashMap<>();
Set<Character> trackUniqueCharacter = new HashSet<>();
Map<Character, Character> map = new HashMap<>();
Set<Character> usedCharacters = new HashSet<>();

for (int i = 0; i < s.length(); i++) {
if (characterMap.containsKey(s.charAt(i))) {
if (t.charAt(i) != characterMap.get(s.charAt(i))) {
char sourceChar = s.charAt(i);
char targetChar = t.charAt(i);

if (map.containsKey(sourceChar)) {
if (map.get(sourceChar) != targetChar) {
return false;
}
} else {
if (trackUniqueCharacter.contains(t.charAt(i))) {
if (usedCharacters.contains(targetChar)) {
return false;
}

characterMap.put(s.charAt(i), t.charAt(i));
map.put(sourceChar, targetChar);
usedCharacters.add(targetChar);
}
trackUniqueCharacter.add(t.charAt(i));
}

return true;
}
}
4 changes: 2 additions & 2 deletions src/test/java/com/thealgorithms/strings/IsomorphicTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ public final class IsomorphicTest {
@ParameterizedTest
@MethodSource("inputs")
public void testCheckStrings(String str1, String str2, Boolean expected) {
assertEquals(expected, Isomorphic.checkStrings(str1, str2));
assertEquals(expected, Isomorphic.checkStrings(str2, str1));
assertEquals(expected, Isomorphic.areIsomorphic(str1, str2));
assertEquals(expected, Isomorphic.areIsomorphic(str2, str1));
}

private static Stream<Arguments> inputs() {
Expand Down
Loading