Skip to content

Commit 4f5e3e8

Browse files
author
rpanjrath
committed
Isomorphic Strings: Adding pattern matching solution.
1 parent 27630d0 commit 4f5e3e8

2 files changed

Lines changed: 49 additions & 15 deletions

File tree

src/strings/isomorphicstrings/Isomorphic.java

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,4 +55,53 @@ public static boolean isIsomorphic(String inputString1, String inputString2) {
5555
return true;
5656
}
5757

58+
public static boolean isIsomorphicUsingPattern(String inputString1, String inputString2) {
59+
int length1 = inputString1.length();
60+
int length2 = inputString2.length();
61+
if (length1 != length2) {
62+
return false;
63+
}
64+
if (length1 == 1) {
65+
return true;
66+
}
67+
Map<Character, Integer> characterMap1 = new HashMap<>();
68+
Map<Character, Integer> characterMap2 = new HashMap<>();
69+
StringBuilder stringBuilder1 = new StringBuilder();
70+
StringBuilder stringBuilder2 = new StringBuilder();
71+
for (int i = 0; i < length1; i++) {
72+
char char1 = inputString1.charAt(i);
73+
char char2 = inputString2.charAt(i);
74+
75+
if (characterMap1.get(char1) == null) {
76+
characterMap1.put(char1, i);
77+
stringBuilder1.append(i);
78+
} else {
79+
stringBuilder1.append(char1);
80+
}
81+
82+
if (characterMap2.get(char2) == null) {
83+
characterMap2.put(char2, i);
84+
stringBuilder2.append(i);
85+
} else {
86+
stringBuilder2.append(char2);
87+
}
88+
89+
if (!stringBuilder1.toString().equalsIgnoreCase(stringBuilder2.toString())) {
90+
return false;
91+
}
92+
}
93+
return true;
94+
}
95+
96+
public static void main(String[] args) {
97+
System.out.println(Isomorphic.isIsomorphic("foo", "bar"));
98+
System.out.println(Isomorphic.isIsomorphic("bar", "foo"));
99+
System.out.println(Isomorphic.isIsomorphicUsingPattern("foo", "bar"));
100+
System.out.println(Isomorphic.isIsomorphicUsingPattern("bar", "foo"));
101+
System.out.println(Isomorphic.isIsomorphic("turtle", "tletur"));
102+
System.out.println(Isomorphic.isIsomorphic("tletur", "turtle"));
103+
System.out.println(Isomorphic.isIsomorphicUsingPattern("turtle", "tletur"));
104+
System.out.println(Isomorphic.isIsomorphicUsingPattern("tletur", "turtle"));
105+
}
106+
58107
}

src/strings/isomorphicstrings/Test.java

Lines changed: 0 additions & 15 deletions
This file was deleted.

0 commit comments

Comments
 (0)