BiruLyu
6/12/2017 - 6:03 PM

## 205. Isomorphic Strings(1st).java

``````public class Solution {
public boolean isIsomorphic(String s, String t) {
HashMap<Character, Character> map1 = new HashMap<Character, Character>();
HashMap<Character, Character> map2 = new HashMap<Character, Character>();
if(s == null || t == null || s.length() != t.length()) return false;
int len = s.length();
for(int i = 0; i < len; i++) {
char temp1 = s.charAt(i);
char temp2 = t.charAt(i);
if(!map1.containsKey(temp1)) {
map1.put(temp1, temp2);
} else if (map1.get(temp1) != temp2){
return false;
}

if(!map2.containsKey(temp2)) {
map2.put(temp2, temp1);
} else if (map2.get(temp2) != temp1){
return false;
}
}
return true;
}
}``````
``````public class Solution {
public boolean isIsomorphic(String s, String t) {

if(s == null || t == null || s.length() != t.length()) return false;
Set<Character> set1 = new HashSet<Character>();
Set<Character> set2 = new HashSet<Character>();
Map<Character,Character> map = new HashMap<Character,Character>();
int len = s.length();
for(int i = 0; i < len; i++) {
char temp1 = s.charAt(i);
char temp2 = t.charAt(i);
map.put(temp1, temp2);
}
return set1.size() == set2.size() && set1.size() == map.size();
}
}

/*
"egg"
"cd"
"aa"
*/``````
``````public class Solution {
public boolean isIsomorphic(String s, String t) {
return helper(s,t) && helper(t,s);
}

private boolean helper (String s, String t){
if (s.length()!= t.length()){
return false;
}
char [] hashmap = new char [256];
for (int i = 0; i<s.length(); i++){
char cS = s.charAt(i);
char cT = t.charAt(i);
if (hashmap[cS]==0){
hashmap[cS] = cT;
} else if (hashmap[cS] != cT){
return false;
}
}
return true;
}
}``````
``````public class Solution {
public boolean isIsomorphic(String s, String t) {
char[] S = s.toCharArray();
char[] T = t.toCharArray();

if(S.length != T.length) return false;

return isIsomorphic(S, T) ;
}

boolean isIsomorphic(char[] S, char[] T) {
char[] MAP = new char[256];
Set<Character> usedMapping = new HashSet<Character>();

for(int i = 0; i < S.length; i++) {

if(MAP[(int)S[i]] == 0) {
// not mapped
if (usedMapping.contains(T[i]))
return false;
MAP[(int)S[i]] = T[i];