Skip to content

Commit 2b187ef

Browse files
Isomorphic Strings: Accepted
1 parent 1d00fe2 commit 2b187ef

2 files changed

Lines changed: 55 additions & 0 deletions

File tree

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -257,6 +257,7 @@ My accepted leetcode solutions to some of the common interview problems.
257257
- [Count and Say](problems/src/string/CountAndSay.java) (Easy)
258258
- [Multiply Strings](problems/src/string/MultiplyStrings.java) (Medium)
259259
- [Longest Word in Dictionary through Deleting](problems/src/string/LongestWordInDictonary.java) (Medium)
260+
- [Isomorphic Strings](problems/src/string/IsomorphicStrings.java) (Easy)
260261

261262
#### [Tree](problems/src/tree)
262263

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package string;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
6+
/**
7+
* Created by gouthamvidyapradhan on 11/04/2018.
8+
* Given two strings s and t, determine if they are isomorphic.
9+
10+
Two strings are isomorphic if the characters in s can be replaced to get t.
11+
12+
All occurrences of a character must be replaced with another character while preserving the order of characters. No
13+
two characters may map to the same character but a character may map to itself.
14+
15+
For example,
16+
Given "egg", "add", return true.
17+
18+
Given "foo", "bar", return false.
19+
20+
Given "paper", "title", return true.
21+
22+
Note:
23+
You may assume both s and t have the same length.
24+
Solution O(N): Maintain two hashmaps and compare character by character.
25+
*/
26+
public class IsomorphicStrings {
27+
/**
28+
* Main method
29+
* @param args
30+
* @throws Exception
31+
*/
32+
public static void main(String[] args) throws Exception{
33+
System.out.println(new IsomorphicStrings().isIsomorphic("abc", "dea"));
34+
}
35+
36+
public boolean isIsomorphic(String s, String t) {
37+
if(s.length() != t.length()) return false;
38+
Map<Character, Character> first = new HashMap<>();
39+
Map<Character, Character> second = new HashMap<>();
40+
for(int i = 0; i < s.length(); i ++){
41+
char c = s.charAt(i);
42+
if(first.containsKey(c)){
43+
char secondC = first.get(c);
44+
if(t.charAt(i) != secondC) return false;
45+
} else{
46+
first.put(c, t.charAt(i));
47+
if(second.containsKey(t.charAt(i))) return false;
48+
second.put(t.charAt(i), c);
49+
}
50+
}
51+
return true;
52+
}
53+
54+
}

0 commit comments

Comments
 (0)