|
| 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