lamiastella

isomorphic

May 26th, 2016
275
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.95 KB | None | 0 0
  1. /**
  2.  * Created by mona on 5/26/16.
  3.  */
  4. import java.util.TreeMap;
  5. import java.util.Map;
  6.  
  7. public class IsomorphicStrings {
  8.     //the words "abca" and "zbxz" are isomorphic
  9.     //aabc a(2) b(1) c(1)
  10.     //my algorithm
  11.     //create a sorted hashmap  on value
  12.     //check to see if two hashmap are equal based on their value set
  13.     //assuming two isomorphic strings are of the same length
  14.  
  15.     public static <Integer, Character> TreeMap reverse(TreeMap<Character,Integer> tmap) {
  16.         TreeMap<Integer,Character> rev = new TreeMap();
  17.         for(Map.Entry<Character,Integer> entry : tmap.entrySet())
  18.             rev.put(entry.getValue(), entry.getKey());
  19.         return rev;
  20.     }
  21.  
  22.     public static boolean areIsomorphic(String s1, String s2) {
  23.         TreeMap<Character, Integer> freqMap1 = new TreeMap<>();
  24.         TreeMap<Character, Integer> freqMap2 = new TreeMap<>();
  25.  
  26.         for (int i=0; i<s1.length(); i++) {
  27.             if (freqMap1.containsKey(s1.charAt(i))) {
  28.                 int freq1 = freqMap1.get(s1.charAt(i));
  29.                 freqMap1.put(s1.charAt(i), freq1 + 1);
  30.             }
  31.             else {
  32.                 freqMap1.put(s1.charAt(i), 1);
  33.             }
  34.  
  35.             if (freqMap2.containsKey(s2.charAt(i))) {
  36.                 int freq2 = freqMap2.get(s2.charAt(i));
  37.                 freqMap1.put(s2.charAt(i), freq2 + 1);
  38.             }
  39.             else {
  40.                 freqMap2.put(s2.charAt(i), 1);
  41.             }
  42.  
  43.         }
  44.  
  45.  
  46.         TreeMap<Integer, Character> sortedFreq1= reverse(freqMap1);
  47.         Integer[] freqArr1 = sortedFreq1.keySet().toArray(new Integer[0]);
  48.         TreeMap<Integer, Character> sortedFreq2= reverse(freqMap2);
  49.         Integer[] freqArr2 = sortedFreq2.keySet().toArray(new Integer[0]);
  50.         return freqArr1.equals(freqArr2);
  51.  
  52.     }
  53.  
  54.     public static void main(String[] args) {
  55.         String s1="abca";
  56.         String s2="zbxz";
  57.         System.out.println(areIsomorphic(s1, s2));
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment