1
+ /* Implementation of Isomorphic Strings problem
2
+ *
3
+ * In this problem, we will be given two strings s and t, we need to determine if they
4
+ * are isomorphic strings or not
5
+ *
6
+ * Two strings s and t are isomorphic if the characters in s can be replaced to get t.
7
+
8
+ * All occurrences of a character must be replaced with another character while preserving
9
+ * the order of characters. No two characters may map to the same character, but a character
10
+ * may map to itself.
11
+ *
12
+ * Problem link: https://leetcode.com/problems/isomorphic-strings/
13
+ *
14
+ */
15
+
16
+ import java .util .*;
17
+ import java .io .*;
18
+
19
+ class IsomorphicStrings
20
+ {
21
+ public boolean isIsomorphic (String s , String t )
22
+ {
23
+ if (t .length () == s .length ())
24
+ {
25
+ Map <Character , Character > sTMap = new HashMap <>();
26
+ Map <Character , Character > tSMap = new HashMap <>();
27
+ for (int i =0 ; i <t .length (); i ++)
28
+ {
29
+ Character sChar = s .charAt (i );
30
+ Character tChar = t .charAt (i );
31
+
32
+ if (sTMap .containsKey (sChar ))
33
+ {
34
+ if (sTMap .get (sChar )!=tChar )
35
+ return false ;
36
+ }
37
+ if (tSMap .containsKey (tChar ))
38
+ {
39
+ if (tSMap .get (tChar )!=sChar )
40
+ return false ;
41
+ }
42
+ sTMap .put (sChar , tChar );
43
+ tSMap .put (tChar , sChar );
44
+ }
45
+ return true ;
46
+ }
47
+ //if s and t have different lengths they cannot be isomorphic
48
+ else
49
+ return false ;
50
+ }
51
+
52
+ public static void main ()
53
+ {
54
+ Scanner sc = new Scanner (System .in );
55
+ String s = sc .next ();
56
+ String t = sc .next ();
57
+ IsomorphicStrings obj = new IsomorphicStrings ();
58
+ System .out .println (obj .isIsomorphic (s ,t ));
59
+ }
60
+ }
61
+
62
+ /*
63
+ Example 1:
64
+
65
+ Input: s = "egg", t = "add"
66
+ Output: true
67
+
68
+ Example 2:
69
+
70
+ Input: s = "foo", t = "bar"
71
+ Output: false
72
+
73
+ Example 3:
74
+
75
+ Input: s = "paper", t = "title"
76
+ Output: true
77
+
78
+ Time Complexity: O(n)
79
+ Space Complexity: O(n) , where n is the length of the input string
80
+ */
0 commit comments