lamiastella

is isomorphic

May 26th, 2016
240
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.03 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.     //create a hashmap sort on value
  11.     //check to see if two hashmap are equal based on their value set
  12.     //assuming two isomorphic strings are of the same length
  13.  
  14.     public static <Integer, Character> TreeMap reverse(TreeMap<Character,Integer> tmap) {
  15.         TreeMap<Integer,Character> rev = new TreeMap();
  16.         for(Map.Entry<Character,Integer> entry : tmap.entrySet())
  17.             rev.put(entry.getValue(), entry.getKey());
  18.         return rev;
  19.     }
  20.  
  21.     public static boolean areIsomorphic(String s1, String s2) {
  22.         char[] charArray1 = s1.toCharArray();
  23.         char[] charArray2 = s2.toCharArray();
  24.         TreeMap<Character, Integer> freqMap1 = new TreeMap<>();
  25.         TreeMap<Character, Integer> freqMap2 = new TreeMap<>();
  26.         for (int i=0; i<charArray1.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