|
5 | 5 | import java.util.Map; |
6 | 6 | import java.util.Set; |
7 | 7 |
|
| 8 | +/** |
| 9 | + * Utility class to check if two strings are isomorphic. |
| 10 | + * |
| 11 | + * <p> |
| 12 | + * Two strings {@code s} and {@code t} are isomorphic if the characters in {@code s} |
| 13 | + * can be replaced to get {@code t}, while preserving the order of characters. |
| 14 | + * Each character must map to exactly one character, and no two characters can map to the same character. |
| 15 | + * </p> |
| 16 | + * |
| 17 | + * @see <a href="https://en.wikipedia.org/wiki/Isomorphism_(computer_science)">Isomorphic Strings</a> |
| 18 | + */ |
8 | 19 | public final class Isomorphic { |
| 20 | + |
9 | 21 | private Isomorphic() { |
10 | 22 | } |
11 | 23 |
|
12 | | - public static boolean checkStrings(String s, String t) { |
| 24 | + /** |
| 25 | + * Checks if two strings are isomorphic. |
| 26 | + * |
| 27 | + * @param s the first input string |
| 28 | + * @param t the second input string |
| 29 | + * @return {@code true} if {@code s} and {@code t} are isomorphic; {@code false} otherwise |
| 30 | + */ |
| 31 | + public static boolean areIsomorphic(String s, String t) { |
13 | 32 | if (s.length() != t.length()) { |
14 | 33 | return false; |
15 | 34 | } |
16 | 35 |
|
17 | | - // To mark the characters of string using MAP |
18 | | - // character of first string as KEY and another as VALUE |
19 | | - // now check occurence by keeping the track with SET data structure |
20 | | - Map<Character, Character> characterMap = new HashMap<>(); |
21 | | - Set<Character> trackUniqueCharacter = new HashSet<>(); |
| 36 | + Map<Character, Character> map = new HashMap<>(); |
| 37 | + Set<Character> usedCharacters = new HashSet<>(); |
22 | 38 |
|
23 | 39 | for (int i = 0; i < s.length(); i++) { |
24 | | - if (characterMap.containsKey(s.charAt(i))) { |
25 | | - if (t.charAt(i) != characterMap.get(s.charAt(i))) { |
| 40 | + char sourceChar = s.charAt(i); |
| 41 | + char targetChar = t.charAt(i); |
| 42 | + |
| 43 | + if (map.containsKey(sourceChar)) { |
| 44 | + if (map.get(sourceChar) != targetChar) { |
26 | 45 | return false; |
27 | 46 | } |
28 | 47 | } else { |
29 | | - if (trackUniqueCharacter.contains(t.charAt(i))) { |
| 48 | + if (usedCharacters.contains(targetChar)) { |
30 | 49 | return false; |
31 | 50 | } |
32 | | - |
33 | | - characterMap.put(s.charAt(i), t.charAt(i)); |
| 51 | + map.put(sourceChar, targetChar); |
| 52 | + usedCharacters.add(targetChar); |
34 | 53 | } |
35 | | - trackUniqueCharacter.add(t.charAt(i)); |
36 | 54 | } |
| 55 | + |
37 | 56 | return true; |
38 | 57 | } |
39 | 58 | } |
0 commit comments