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