Pages

Monday, 12 October 2015

Check if two given strings are isomorphic to each other

Check if two given strings are isomorphic to each other

Given two strings s and t, determine if they are isomorphic. Two strings are isomorphic if the characters in s can be replaced to get t.

All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.

For example,
Given "egg", "add", return true.
Given "foo", "bar", return false.
Given "paper", "title", return true.



public class TestIsomorphic {
      public static void main(String[] args) {
            String str1 = "abb";
            String str2 = "axx";
            boolean res = TestIsomorphic.checkIsomorphic(str1,str2);
            System.out.println(res);
      }

      static boolean checkIsomorphic(String str1, String str2) {
            int length = str1.length();
            /* length of both strings must be same */
            if (length != str2.length()) {
                  return false;
            }

            // To mark visited characters in str2
            char visited[] = new char[26];
            for (int i = 0; i < visited.length; i++) {
                  visited[i] = '#';
            }

            char[] strArr1 = str1.toCharArray();
            char[] strArr2 = str2.toCharArray();

            // Process all characters one by on
            for (int i = 0; i<length; i++) {
                  char ch = visited[strArr1[i]-'a'];
                  if(ch=='#') {
                        visited[strArr1[i]-'a'] = strArr2[i];
                  } else if (ch != strArr2[i]) {
                        return false;                      
                  }
            }
            return true;
      }
}
Output: true

No comments:

Post a Comment